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

Parent

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)
Post
+1
−0

Disclaimer: I don't work with EF therefore not an expert. EF is tricky and has a lot of dark magic inside so if you're not sure how it all works best to use good old plain SQL or simple libraries.


I think you see this behaviour because you return old "blog" object, which isn't the same as new "blog" that you wrote to the db.

So I suppose your intention was to return "new" blog instead, e.g:

    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;
        return context.Blogs.First();
    }

with this change it prints


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 (edited): I wrote an app using EF Core!
Goodbye World: Some content

Hints:

  1. You can track state of entities by using ChangeTracker
context.ChangeTracker.DetectChanges();
Console.WriteLine(context.ChangeTracker.DebugView.LongView);
  1. EF automatically detects changes so you don't have to use "Updates" explicitly
History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

1 comment thread

You can do `var blogEntity = context.Add(blog);` so you can `return blogEntity.Entity;` (1 comment)
You can do `var blogEntity = context.Add(blog);` so you can `return blogEntity.Entity;`
rene‭ wrote over 1 year ago

You can do var blogEntity = context.Add(blog); so you can return blogEntity.Entity;