Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on Updating the database reverses previous changes

Post

Updating the database reverses previous changes

+3
−0

The Code

using Microsoft.EntityFrameworkCore;

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    public string DbPath { get; }

    public BloggingContext()
    {
        DbPath = "blogging.db";
    }

    // The following configures EF to create a Sqlite database file in the
    // special "local" folder for your platform.
    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite($"Data Source={DbPath}");
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }

    public List<Post> Posts { get; } = new();
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }

    public int BlogId { get; set; }
    public Blog Blog { get; set; }
}

public class Program
{
    public static void Main()
    {
        var blog = SetupBlog();
        var posts = GetPosts(blog);

        PrintPosts("Initial posts", posts);

        var post = posts.First();
        post.Title = "Hello World (edited)";
        SavePost(post);

        PrintPosts("After editing", GetPosts(blog));

        var newPost = new Post
        {
            Blog = blog,
            Title = "Goodbye World",
            Content = "Some content"
        };

        SavePost(newPost);

        PrintPosts("After adding a new post", GetPosts(blog));

        Remove(blog);
    }

    static void PrintPosts(string header, IEnumerable<Post> posts)
    {
        Console.WriteLine($"\n{header}\n{new string('=', header.Length)}");
        foreach (var post in posts)
        {
            Console.WriteLine($"{post.Title}: {post.Content}");
        }
    }

    static void Remove(Blog blog)
    {
        using var context = new BloggingContext();
        context.Remove(blog);
        context.SaveChanges();
    }

    static Blog SetupBlog()
    {
        using var context = new BloggingContext();

        var blog = new Blog { Url = "http://blogs.msdn.com/adonet" };
        blog.Posts.Add(new Post { Title = "Hello World", Content = "I wrote an app using EF Core!" });
        context.Add(blog);
        context.SaveChanges();

        return blog;
    }

    static Post[] GetPosts(Blog blog)
    {
        using var context = new BloggingContext();
        return context.Posts.Where(p => p.BlogId == blog.BlogId).ToArray();
    }

    static void SavePost(Post post)
    {
        using var context = new BloggingContext();
        context.Posts.Update(post);
        context.SaveChanges();
    }
}

Output

Initial posts
=============
Hello World: I wrote an app using EF Core!

After editing
=============
Hello World (edited): I wrote an app using EF Core!

After adding a new post
=======================
Hello World: I wrote an app using EF Core!
Goodbye World: Some content

The Problem

For some reason, the first post is being reset after adding the new one. I'm not sure why though.

The post is clearly being saved to the database after being edited, as shown by the output above.

I also create a new context in each method, so I don't think this is an issue with contexts having stale data.

Therefore, the only thing I can think of is that the Update statement is somehow undoing the previous edit. It really doesn't make sense as to why it would do that though.

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

Try to not reuse modals across multiple transactions (2 comments)
Try to not reuse modals across multiple transactions
Alexei‭ wrote over 1 year ago

I cannot check right now what happens by generating data in the database and actually run the code, but the fact that you are using entities across "database context boundaries" (e.g. blog is obtained as an entity from a disposed context and then used in other database contexts) is a red flag for me.

Typically, in an application (especially the complex ones) we should aim for one database context transaction per scenario (e.g. in ASP.NET Core db contexts are scoped to the requests, are injected and implicitly disposed at the end of the request scope).

One way to check is to isolate the operations (do not reuse the blog instance, reload data from the db).

Moshi‭ wrote over 1 year ago

I thought that it wouldn't really matter since EF core would handle it for me (I was reading https://learn.microsoft.com/en-us/ef/core/saving/disconnected-entities which is similar to my use case)