Sub topic 2
Creating the Database with Migrations
Building the Database with Migrations
A migration is a small file of code that describes how to change the database to match your classes. EF Core compares your model to the last migration and writes the difference for you.
Run these two commands in your project folder:
dotnet ef migrations add InitialCreate
dotnet ef database updateThe first command creates the migration. The second one applies it. Together they create blogging.db with a Blogs table and a Posts table.
Reading, Adding, Updating, and Deleting
LINQ is a set of C# methods, such as Where and OrderBy, for asking questions about data. EF Core turns your LINQ into SQL. SaveChangesAsync sends any new, changed, or removed objects to the database.
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();
// 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();Why Async Methods
An async method is one that lets your program do other work while it waits for the database. Methods that end in Async, such as FirstAsync and SaveChangesAsync, are used with await. Use them whenever you can, especially in web apps.
Relationships and Loading Related Data
A relationship links rows in two tables. In this model, one blog has many posts. This is called a one-to-many relationship. Post.BlogId is the foreign key, which is a column that points to a row in another table. Blog.Posts and Post.Blog are navigation properties. A navigation property lets you move from one object to its related objects.
EF Core does not load related data unless you ask for it. Include asks for it in the same query, which is called eager loading. Select picks only the columns you need.
using Microsoft.EntityFrameworkCore;
using var db = new BloggingContext();
var blogsWithPosts = await db.Blogs
.AsNoTracking()
.Include(b => b.Posts)
.ToListAsync();
var titles = await db.Posts
.Where(p => p.Blog.Url.StartsWith("https://"))
.Select(p => new { p.Title, BlogUrl = p.Blog.Url })
.ToListAsync();Exercise
You loaded a blog with db.Blogs.FirstAsync(), but blog.Posts is empty even though the database has posts for it. Why, and how do you fix it?
Show answer
EF Core does not load related data on its own. Add .Include(b => b.Posts) before FirstAsync() so the posts are loaded in the same query.