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
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.
Post
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:
- You can track state of entities by using
ChangeTracker
context.ChangeTracker.DetectChanges();
Console.WriteLine(context.ChangeTracker.DebugView.LongView);
- EF automatically detects changes so you don't have to use "Updates" explicitly
1 comment thread