Sub topic 8
Adding, Updating, and Deleting Data
Reading data is only half the job. Most apps also need to save new data, change existing data, and remove data. EF Core handles all three with one method: SaveChanges.
The Basic Idea
The DbContext keeps track of the objects it knows about. This is called change tracking. Change tracking is the context's record of which objects are new, which have changed, and which should be removed.
You change your C# objects in normal ways. Nothing goes to the database yet. When you call SaveChangesAsync, EF Core looks at its record and writes the right SQL: INSERT for new objects, UPDATE for changed ones, and DELETE for removed ones.
A Worked Example
This code uses the Blog, Post, and BloggingContext classes from earlier chapters. Put it in Program.cs and run it with dotnet run.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
// Create
var blog = new Blog { Url = "https://example.com/blog" };
db.Blogs.Add(blog);
await db.SaveChangesAsync();
Console.WriteLine($"New blog id: {blog.BlogId}");
// Read
var found = await db.Blogs
.Where(b => b.Url.Contains("example"))
.OrderBy(b => b.BlogId)
.FirstAsync();
// Update
found.Url = "https://example.com/new-blog";
found.Posts.Add(new Post { Title = "Hello", Content = "First post" });
await db.SaveChangesAsync();
// Delete
db.Blogs.Remove(found);
await db.SaveChangesAsync();Here is what each step does.
- Create.
Addmarks the blog as new.SaveChangesAsyncruns anINSERT. The database then gives the blog a key value, and EF Core copies it intoblog.BlogId. - Read. The query loads one blog. The context starts tracking it.
- Update. Here you just set a property. You do not call any "update" method. EF Core notices that the
Urlchanged and that a new post was added toPosts. It sends anUPDATEfor the blog and anINSERTfor the post. It also fills in the post'sBlogIdfor you. - Delete.
Removemarks the blog for deletion.SaveChangesAsyncruns aDELETE.
One Save, Many Changes
You can make many changes and then call SaveChangesAsync once. EF Core sends all of them together and runs them in a single transaction. A transaction is a group of changes that either all succeed or all fail. If one statement fails, none of the changes are kept.
SaveChangesAsync returns the number of rows it changed. You can use that number to check your work.
You may see the methods SaveChanges and SaveChangesAsync. They do the same work. The async version does not block your program while it waits for the database. A later chapter covers async methods in more detail.
Exercise
You load a blog with a query, set its Url property to a new value, and call SaveChangesAsync. You never call Update or Add. What SQL does EF Core send, and why?
Show answer
It sends an UPDATE statement for that blog. The context was tracking the blog from the moment the query loaded it, so it detected that Url had changed and wrote only that change to the database.
Exercise
Your code calls db.Blogs.Add(newBlog) three times for three different blogs and then calls SaveChangesAsync once. How many blogs are saved if the second insert fails?
Show answer
None. All changes from one SaveChangesAsync call run in a single transaction, so if any statement fails, all of them are rolled back.