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.
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.
2 answers
I did not find the exact cause of your issue, but inserts should not be treated as updates. One way to do this is the following:
static void InsertPost(Post post)
{
using var context = new BloggingContext();
context.Posts.Add(post);
context.SaveChanges();
}
var newPost = new Post
{
BlogId = blog.BlogId,
Title = "Goodbye World",
Content = "Some content"
};
No need to use the navigation property, since we have the BlogId for the new post.
However, it is not recommended for the EF db contexts to leak models like this. As already noticed, it might lead to strange behavior, hard to debug and maintain software.
I would split all operations into independent "use cases". The code would look like the following:
public static void Main()
{
int blogId = SetupBlog();
var posts = GetPosts(blogId);
PrintPosts("Initial posts", posts);
UpdateFirstPostTitle(blogId);
PrintPosts("After editing", GetPosts(blogId));
InsertPost(blogId);
PrintPosts("After adding a new post", GetPosts(blogId));
Remove(blogId);
}
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(int blogId)
{
using var context = new BloggingContext();
var blog = context.Blogs.Find(blogId);
if (blog != null)
{
context.Remove(blog);
context.SaveChanges();
}
}
static int 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.BlogId;
}
static Post[] GetPosts(int blogId)
{
using var context = new BloggingContext();
return context.Posts.Where(p => p.BlogId == blogId).ToArray();
}
static void InsertPost(int blogId)
{
using var context = new BloggingContext();
var newPost = new Post
{
BlogId = blogId,
Title = "Goodbye World",
Content = "Some content"
};
context.Posts.Add(newPost);
context.SaveChanges();
}
static void UpdateFirstPostTitle(int blogId)
{
using var context = new BloggingContext();
var post = context.Posts.First(p => p.BlogId == blogId);
post.Title = "Hello World (edited)";
context.SaveChanges();
}
Instead of reusing models from other context instances, we are working with ids and all the operations are clear and isolated.
0 comment threads
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