TExcelTAD
Home › ASP.NET Core › EF Core Relationships

EF Core Relationships

Real data is connected: a blog has many posts, a post can carry many tags, a user has one profile. EF Core models these connections with navigation properties (references to other entities) and foreign keys, and it creates the matching tables and constraints in migrations.

The three kinds

Relationship Example How it is stored
One-to-many Blog → Posts BlogId foreign key column in Posts
One-to-one Post → PostStats Unique foreign key PostId in PostStats
Many-to-many Post ↔ Tags Hidden join table PostTag (PostsId, TagsId)

One-to-many

You have already seen this one. Each side has a navigation, and the dependent side (Post) holds the foreign key:

csharp
public class Blog
{
    public int Id { get; set; }
    public required string Title { get; set; }
    public List<Post> Posts { get; set; } = [];   // collection navigation
}

public class Post
{
    public int Id { get; set; }
    public required string Title { get; set; }
    public int BlogId { get; set; }               // foreign key (required, because int is not nullable)
    public Blog Blog { get; set; } = null!;       // reference navigation
    public List<Tag> Tags { get; set; } = [];
}

EF Core discovers this by convention. If you prefer to be explicit, or need to change the delete behaviour, use the Fluent API:

csharp
modelBuilder.Entity<Blog>()
    .HasMany(b => b.Posts)
    .WithOne(p => p.Blog)
    .HasForeignKey(p => p.BlogId)
    .OnDelete(DeleteBehavior.Cascade);   // deleting a blog deletes its posts
DeleteBehavior Effect when the principal (Blog) is deleted
Cascade Dependents are deleted too (default for required relationships)
Restrict / NoAction Delete fails while dependents exist
SetNull Foreign key set to NULL (needs a nullable FK such as int?)
ClientSetNull EF sets loaded dependents' FK to null; default for optional relationships

Many-to-many

Give both entities a collection navigation and EF Core creates the join table for you:

csharp
public class Tag
{
    public int Id { get; set; }
    public required string Name { get; set; }
    public List<Post> Posts { get; set; } = [];
}

Adding a tag to a post is just adding to a list:

csharp
var post = await db.Posts.Include(p => p.Tags).FirstAsync(p => p.Id == 3);
var tag = await db.Tags.FirstOrDefaultAsync(t => t.Name == "baking")
          ?? new Tag { Name = "baking" };
post.Tags.Add(tag);
await db.SaveChangesAsync();   // INSERT into Tags (if new) and into PostTag

Loading related data

Navigations are not loaded automatically. A query for blogs returns blogs with empty Posts lists unless you ask for them. You have three options:

Strategy How When
Eager loading Include(b => b.Posts).ThenInclude(p => p.Tags) You know you need the related data
Projection Select(b => new { b.Title, Count = b.Posts.Count }) Best for APIs — fetch only what you return
Explicit loading await db.Entry(blog).Collection(b => b.Posts).LoadAsync() Load later, on demand
csharp
app.MapGet("/blogs/{id:int}", async (int id, AppDbContext db) =>
    await db.Blogs
        .Where(b => b.Id == id)
        .Select(b => new
        {
            b.Id,
            b.Title,
            Posts = b.Posts.OrderBy(p => p.Title).Select(p => new
            {
                p.Title,
                Tags = p.Tags.Select(t => t.Name).ToList()
            }).ToList()
        })
        .FirstOrDefaultAsync()
    is { } blog ? Results.Ok(blog) : Results.NotFound());
bash · try it yourself
$ curl -s localhost:5000/blogs/1
{"id":1,"title":"Kitchen Notes","posts":[{"title":"Knife skills","tags":["basics"]},{"title":"Perfect rice","tags":["basics","grains"]}]}

The runnable version below performs the same "include" by hand with LINQ over in-memory tables, including the join table for the many-to-many relationship:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Linq;

var blogs = new[] { new Blog(1, "Kitchen Notes"), new Blog(2, "Bike Repairs") };
var posts = new[]
{
    new Post(1, "Knife skills", 1), new Post(2, "Chain cleaning", 2),
    new Post(3, "Perfect rice", 1), new Post(4, "Brake pads", 2),
};
var tags = new[] { new Tag(1, "basics"), new Tag(2, "grains"), new Tag(3, "safety") };
var postTag = new[] { new PostTag(1, 1), new PostTag(3, 1), new PostTag(3, 2), new PostTag(4, 3) };   // join table

foreach (var blog in blogs)
{
    Console.WriteLine(
quot;{blog.Title}"); var blogPosts = posts.Where(p => p.BlogId == blog.Id).OrderBy(p => p.Title); foreach (var post in blogPosts) { var names = from pt in postTag where pt.PostId == post.Id join t in tags on pt.TagId equals t.Id select t.Name; Console.WriteLine(
quot; - {post.Title} [{string.Join(", ", names)}]"); } } // Reverse direction: which posts use each tag? foreach (var tag in tags) { int count = postTag.Count(pt => pt.TagId == tag.Id); Console.WriteLine(
quot;#{tag.Name}: {count} post(s)"); } record Blog(int Id, string Title); record Post(int Id, string Title, int BlogId); record Tag(int Id, string Name); record PostTag(int PostId, int TagId);
Kitchen Notes
  - Knife skills [basics]
  - Perfect rice [basics, grains]
Bike Repairs
  - Brake pads [safety]
  - Chain cleaning []
#basics: 2 post(s)
#grains: 1 post(s)
#safety: 1 post(s)

The JSON cycle trap

If you return entities directly, blog.Posts[0].Blog.Posts[0].Blog… is a loop, and System.Text.Json throws a JsonException ("A possible object cycle was detected"). This program reproduces the problem and shows one fix:

csharp · try it yourself
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

var blog = new Blog { Id = 1, Title = "Kitchen Notes" };
blog.Posts.Add(new Post { Id = 3, Title = "Perfect rice", Blog = blog });

try
{
    JsonSerializer.Serialize(blog);
}
catch (JsonException)
{
    Console.WriteLine("JsonException: object cycle detected");
}

var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
{
    ReferenceHandler = ReferenceHandler.IgnoreCycles
};
Console.WriteLine(JsonSerializer.Serialize(blog, options));

class Blog
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    public List<Post> Posts { get; set; } = new();
}

class Post
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    public Blog? Blog { get; set; }
}
JsonException: object cycle detected
{"id":1,"title":"Kitchen Notes","posts":[{"id":3,"title":"Perfect rice","blog":null}]}

Tip: IgnoreCycles works (you can set it for minimal APIs with builder.Services.ConfigureHttpJsonOptions(o => o.SerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles)), but the cleaner fix is to return DTOs or anonymous projections, as in the /blogs/{id} endpoint above. They also stop you from leaking columns you did not intend to expose.

Avoiding N+1 queries

Looping over blogs and loading each blog's posts separately sends one query per blog — the N+1 problem. Use Include or a projection so EF Core fetches everything in one round trip (or a few, with AsSplitQuery() for large collections).

Test yourself

In a Blog → Posts one-to-many relationship, which table holds the foreign key?

  1. Blogs
  2. Posts
  3. A separate join table
  4. Both tables

You query db.Blogs.ToListAsync() and every blog.Posts list is empty, although posts exist. Why?

  1. The relationship is misconfigured
  2. Navigations are not loaded unless you use Include, a projection or explicit loading
  3. SQLite does not support relationships
  4. AsNoTracking is required

What does EF Core create for a many-to-many relationship with two collection navigations and no join entity class?

  1. Nothing, it is not supported
  2. A JSON column
  3. A foreign key on both tables
  4. A join table with two foreign keys