Sub topic 10
Modeling Relationships Between Entities
Real data is connected. A blog has many posts. A post can have many tags. In a database, a foreign key links these rows together. A foreign key is a column in one table that holds the primary key of a row in another table. EF Core lets you describe these links with ordinary C# properties, and it builds the foreign keys for you.
This chapter covers the two most common kinds of relationship: one-to-many and many-to-many. You will also see how to save related objects together and what happens when you delete them.
Key Terms
Here are the words this chapter uses.
| Term | Meaning |
|---|---|
| Relationship | A link between two entity types, such as Blog and Post |
| Principal | The "parent" side of a relationship. Blog is the principal of Post. |
| Dependent | The "child" side. It holds the foreign key. Post is the dependent. |
| Navigation property | A property that points to a related object or a list of them, such as `Blog.Posts` |
| Foreign key property | A property that stores the related row's key, such as `Post.BlogId` |
| Join table | An extra table that links two tables in a many-to-many relationship |
One-to-Many Relationships
A one-to-many relationship means one row on the principal side can link to many rows on the dependent side. One blog has many posts. Each post belongs to exactly one blog.
You already met this model earlier in the tutorial:
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; } = null!;
}EF Core finds this relationship by convention, which means a built-in naming rule. You never write a line of setup code for it. Here is what EF Core sees:
Blog.Postsis a list ofPost. That is a collection navigation. It points to many objects.Post.Blogis a singleBlog. That is a reference navigation. It points to one object.Post.BlogIdmatches the pattern "navigation name + key name". EF Core treats it as the foreign key.
In the database, the Posts table gets a BlogId column with a foreign key constraint that points at Blogs.BlogId.
Required and Optional Relationships
The type of the foreign key controls whether a post must have a blog.
int BlogIdcannot be null, so every post must have a blog. This is a required relationship.int? BlogIdcan be null, so a post may exist without a blog. This is an optional relationship.
For an optional relationship, make the navigation nullable too: public Blog? Blog { get; set; }.
Many-to-Many Relationships
A many-to-many relationship means rows on both sides can link to many rows on the other side. A post can have many tags, and a tag can label many posts.
A database cannot store this with a single foreign key column. It needs a join table, where each row holds one post ID and one tag ID. Since EF Core 5, you do not need to write a class for the join table. Put a collection navigation on each side and EF Core creates the table for you.
Add a Tag class and a Tags list on Post. This is the full model, ready to replace the earlier version:
using Microsoft.EntityFrameworkCore;
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; } = null!;
public List<Tag> Tags { get; } = new();
}
public class Tag
{
public int TagId { get; set; }
public string Name { get; set; } = "";
public List<Post> Posts { get; } = new();
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs => Set<Blog>();
public DbSet<Post> Posts => Set<Post>();
public DbSet<Tag> Tags => Set<Tag>();
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite("Data Source=blogging.db");
}EF Core sees Post.Tags and Tag.Posts, two collections that point at each other. It creates a join table named PostTag with two columns: PostsPostId and TagsTagId. Together, those two columns form the join table's primary key, so the same tag cannot be added to the same post twice.
Update the Database
You changed the model, so the schema must change too. Create and apply a new migration:
dotnet ef migrations add AddTags
dotnet ef database updateThe migration creates the Tags table and the PostTag join table.
Saving Related Data
Because the relationships are plain C# properties, you build related data the same way you build any object graph. An object graph is a group of objects that point to each other. Add the top object to the context, and EF Core finds and inserts the rest.
using var db = new BloggingContext();
var csharp = new Tag { Name = "csharp" };
var efcore = new Tag { Name = "efcore" };
var post = new Post { Title = "Relationships", Content = "Posts and tags" };
post.Tags.Add(csharp);
post.Tags.Add(efcore);
var blog = new Blog { Url = "https://example.com/relations" };
blog.Posts.Add(post);
db.Blogs.Add(blog);
await db.SaveChangesAsync();
Console.WriteLine($"Blog {blog.BlogId}, post {post.PostId}, post.BlogId {post.BlogId}");
Console.WriteLine($"Tags on post: {post.Tags.Count}");Notice that you never set post.BlogId yourself. During SaveChangesAsync, EF Core takes these steps:
- It inserts the blog and reads back its new
BlogId. - It copies that value into
post.BlogId, a step called fixup. - It inserts the post and both tags.
- It inserts two rows into
PostTag, one for each tag.
You can also link to an object that already exists. For example, post.BlogId = 3; attaches a new post to blog 3 without loading that blog first.
Deleting Related Data
What happens to posts when you delete their blog? For a required relationship, EF Core uses cascade delete by default. Deleting the blog also deletes its posts, because a post cannot exist without a blog.
For an optional relationship (int? BlogId), the default changes. EF Core sets BlogId to null on any posts it is tracking, and the posts stay.
In a many-to-many relationship, deleting a post removes only its rows in PostTag. The tags themselves remain.
A Brief Look at One-to-One
A one-to-one relationship links one row to at most one other row, for example a blog and its single header image. You write it with a reference navigation on both sides and a foreign key on the dependent. Because neither side is a list, EF Core sometimes cannot tell which side is the dependent. In those cases, you name it with the Fluent API, which the chapter on model configuration covers.
Summary
- Navigation properties describe relationships in C#. Foreign key properties store the links in the database.
- EF Core discovers one-to-many relationships by convention from names like
Blog.Posts,Post.Blog, andPost.BlogId. - A non-nullable foreign key makes a relationship required. A nullable one makes it optional.
- Two collection navigations that point at each other create a many-to-many relationship with an automatic join table.
- Add an object graph once, and
SaveChangesAsyncinserts every object and fills in the keys.
Exercise
You want posts to be able to exist without belonging to any blog. What two changes do you make to the Post class, and what happens to those posts when their blog is deleted?
Show answer
Change public int BlogId to public int? BlogId, and change the navigation to public Blog? Blog { get; set; }. The relationship becomes optional. When the blog is deleted, EF Core sets BlogId to null on the posts it is tracking instead of deleting them.
Exercise
Add a Category entity so each post can be in many categories and each category can hold many posts. Which properties do you add, and what extra table does the migration create?
Show answer
Create public class Category { public int CategoryId { get; set; } public string Name { get; set; } = ""; public List<Post> Posts { get; } = new(); }, add public List<Category> Categories { get; } = new(); to Post, and add public DbSet<Category> Categories => Set<Category>(); to the context. After dotnet ef migrations add AddCategories, the migration creates a Categories table and a join table named CategoryPost with the columns CategoriesCategoryId and PostsPostId.
Exercise
In the saving example, the code never sets post.BlogId, yet it prints a real number after SaveChangesAsync. Why?
Show answer
The post was added to blog.Posts, so EF Core knows the two are related. When it inserts the blog and gets its generated BlogId, it copies that value into post.BlogId (fixup) before inserting the post.