Sub topic 8
Adding, Updating, and Deleting Data
In the last chapter you read data with LINQ. Now you will change it. This chapter shows how to add new rows, change existing rows, and remove rows, all with plain C# objects. You will also see how one method, SaveChangesAsync, sends your changes to the database.
The examples use the Blog, Post, and BloggingContext classes you built earlier, with the blogging.db database you created with migrations.
The Big Idea: Change Objects, Then Save
When you use EF Core, you do not write INSERT, UPDATE, or DELETE statements yourself. You work with objects instead:
- You add, change, or remove objects through the context.
- The context keeps a list of what you changed.
- You call
SaveChangesAsync. EF Core turns the list into SQL commands and runs them.
Nothing reaches the database until step 3. If you skip the save, your changes stay in memory and are lost when the program ends.
Entity States
The context gives each object it knows about a state. The state is a label that tells EF Core which SQL command to run on save. Here are the states you will see in this chapter:
| State | Meaning | SQL on save |
|---|---|---|
| Added | A new object that is not in the database yet | `INSERT` |
| Unchanged | Loaded from the database and not changed | None |
| Modified | Loaded from the database, then changed | `UPDATE` |
| Deleted | Marked for removal | `DELETE` |
| Detached | The context is not watching this object | None |
A later chapter, "How Change Tracking Works", explains how EF Core notices your edits. In this chapter you only need to know that it does.
Adding Data
To add a row, create an object and pass it to Add:
using var db = new BloggingContext();
var blog = new Blog { Url = "https://example.com/blog" };
db.Blogs.Add(blog);
Console.WriteLine(db.Entry(blog).State); // Added
Console.WriteLine(blog.BlogId); // 0
await db.SaveChangesAsync();
Console.WriteLine(db.Entry(blog).State); // Unchanged
Console.WriteLine(blog.BlogId); // 1 (or the next free number)Look at BlogId. Before the save it is 0. The database creates the real key when it inserts the row, and EF Core copies that key back into your object. After the save you can use blog.BlogId right away.
On SQLite, the SQL that EF Core runs looks roughly like this:
INSERT INTO "Blogs" ("Url")
VALUES (@p0)
RETURNING "BlogId";@p0 is a parameter, a placeholder that holds your value. EF Core always sends values as parameters, which keeps your data safe from SQL injection.
To add several objects at once, use AddRange:
db.Blogs.AddRange(
new Blog { Url = "https://example.com/a" },
new Blog { Url = "https://example.com/b" });
await db.SaveChangesAsync();Updating Data
To update a row, load it, change its properties, and save:
using var db = new BloggingContext();
var found = await db.Blogs
.Where(b => b.Url.Contains("example"))
.OrderBy(b => b.BlogId)
.FirstAsync();
found.Url = "https://example.com/new-blog";
await db.SaveChangesAsync();You never call an "update" method. The context loaded found, so it watches the object. When you save, it sees that Url changed and sends an UPDATE:
UPDATE "Blogs" SET "Url" = @p0
WHERE "BlogId" = @p1;Only the changed column is in the SET part. If you change nothing, SaveChangesAsync sends no SQL at all.
Adding Related Data
You can add a post by putting it in a blog's Posts list:
found.Posts.Add(new Post { Title = "Hello", Content = "First post" });
await db.SaveChangesAsync();You did not set BlogId on the post. EF Core sees that the post is inside found.Posts, so it fills in the foreign key for you. A foreign key is a column that points to a row in another table. Here, Post.BlogId points to the blog.
Deleting Data
To delete a row, pass a loaded object to Remove and save:
db.Blogs.Remove(found);
await db.SaveChangesAsync();This sends a DELETE ... WHERE "BlogId" = @p0 command.
What happens to the blog's posts? Post.BlogId is an int, which cannot be null, so every post must belong to a blog. Because of that, EF Core sets up cascade delete by convention. Cascade delete means that deleting a blog also deletes its posts. Your migration added this rule to the database, too.
Many Changes, One Save
You can make many changes and save once:
db.Blogs.Add(new Blog { Url = "https://example.com/c" });
found.Url = "https://example.com/renamed";
db.Posts.Remove(oldPost);
await db.SaveChangesAsync();EF Core runs all three commands inside one transaction. A transaction is a group of commands that succeed or fail together. If the DELETE fails, the INSERT and UPDATE are rolled back (undone). Your database is never left half-changed. "Working with Transactions", later in this tutorial, shows how to group several saves.
A Complete Worked Example
This Program.cs creates, reads, updates, and deletes a blog. Keep your Blog, Post, and BloggingContext classes in a separate file, such as Models.cs.
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($"Created blog {blog.BlogId}");
// Read
var found = await db.Blogs
.Where(b => b.Url.Contains("example"))
.OrderBy(b => b.BlogId)
.FirstAsync();
Console.WriteLine($"Found blog {found.BlogId}: {found.Url}");
// Update
found.Url = "https://example.com/new-blog";
found.Posts.Add(new Post { Title = "Hello", Content = "First post" });
await db.SaveChangesAsync();
Console.WriteLine($"Posts in database: {await db.Posts.CountAsync()}");
// Delete
db.Blogs.Remove(found);
await db.SaveChangesAsync();
Console.WriteLine($"Blogs left: {await db.Blogs.CountAsync()}");Run it with dotnet run. If the database was empty, the output ends with Blogs left: 0. The post was removed with its blog by cascade delete.
Common Mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Forgetting `SaveChangesAsync` | Nothing is written to the database | Call it after your changes |
| Leaving out `await` | The save may not finish before the next line runs | Write `await db.SaveChangesAsync();` |
| Loading in one context, saving in another | The second context does not know about the object, so it saves nothing | Use the same context for loading and saving |
| Reading `BlogId` before saving | It is still `0` | Read the key after the save |
| Deleting a parent without thinking | Its children are deleted too | Check dependent rows first |
Exercise
You load a blog, set its Url to a new value, and the program ends without calling SaveChangesAsync. What Url does the database hold?
Show answer
The old Url. Changes stay in the context's memory until SaveChangesAsync runs, so nothing was sent to the database.
Exercise
You call db.Blogs.Add(blog) but have not saved yet. What is the value of blog.BlogId, and what is the entity's state?
Show answer
BlogId is 0 and the state is Added. The database creates the real key during the INSERT, and EF Core copies it into the object when SaveChangesAsync finishes.
Exercise
Write code that loads the blog with BlogId 1, adds two posts to it, and saves both with one call.
Show answer
var b = await db.Blogs.FirstAsync(x => x.BlogId == 1); b.Posts.Add(new Post { Title = "One", Content = "A" }); b.Posts.Add(new Post { Title = "Two", Content = "B" }); await db.SaveChangesAsync(); EF Core sets BlogId on both posts and inserts them in a single transaction.