EF Core Relationships: One-to-Many and Many-to-Many
Relationships in a Real Database
| Type | Example | In the database |
|---|---|---|
| One-to-many | One author, many books | Foreign key AuthorId in Books |
| One-to-one | One user, one profile | Foreign key with unique constraint |
| Many-to-many | Books and tags | A join table with two foreign keys |
One-to-Many
csharp
public class Author
{
public int Id { get; set; }
public required string Name { get; set; }
public List<Book> Books { get; set; } = [];
}
public class Book
{
public int Id { get; set; }
public required string Title { get; set; }
public int AuthorId { get; set; }
public Author Author { get; set; } = null!;
}
EF finds the relationship by convention. The AuthorId property is the foreign key.
Many-to-Many
csharp
public class Tag
{
public int Id { get; set; }
public required string Name { get; set; }
public List<Book> Books { get; set; } = [];
}
// in Book add:
// public List<Tag> Tags { get; set; } = [];
// EF creates the join table BookTag automatically.
var book = await db.Books.Include(b => b.Tags).FirstAsync();
book.Tags.Add(new Tag { Name = "Classic" });
await db.SaveChangesAsync();
Loading Related Data
EF does not load related objects unless you ask.
csharp
var books = await db.Books
.Include(b => b.Author) // load the author with each book
.Include(b => b.Tags)
.ToListAsync();
var authors = await db.Authors
.Include(a => a.Books)
.ThenInclude(b => b.Tags)
.ToListAsync();
The N+1 Problem
csharp
// BAD: one query for books, then one more query PER book to read its author
foreach (var b in await db.Books.ToListAsync())
Console.WriteLine(b.Author.Name); // lazy loading would fire here
// GOOD: one query with a JOIN
foreach (var b in await db.Books.Include(b => b.Author).ToListAsync())
Console.WriteLine(b.Author.Name);
// BEST for read-only screens: project exactly what you need
var rows = await db.Books.Select(b => new { b.Title, Author = b.Author.Name }).ToListAsync();
Fluent API Configuration
csharp
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Book>(entity =>
{
entity.Property(b => b.Title).HasMaxLength(200).IsRequired();
entity.Property(b => b.Price).HasPrecision(10, 2);
entity.HasIndex(b => b.Isbn).IsUnique();
entity.HasOne(b => b.Author)
.WithMany(a => a.Books)
.HasForeignKey(b => b.AuthorId)
.OnDelete(DeleteBehavior.Restrict); // cannot delete an author who has books
});
modelBuilder.Entity<Book>().Property(b => b.Status).HasConversion<string>(); // enum stored as text
}
| Delete behavior | Result when the parent is deleted |
|---|---|
Cascade | Children are deleted too |
Restrict | Delete is refused if children exist |
SetNull | Foreign key becomes null |
Global Query Filters (Soft Delete)
csharp
modelBuilder.Entity<Book>().HasQueryFilter(b => !b.IsDeleted);
// all queries now exclude deleted books automatically.
var all = await db.Books.IgnoreQueryFilters().ToListAsync(); // bypass when needed
Tip: Keep entity classes simple and put the configuration in separate
IEntityTypeConfiguration<T> classes when the model grows. Register them with modelBuilder.ApplyConfigurationsFromAssembly(...).
Conclusion
Relationships are navigation properties plus a foreign key. Use Include or projection to load related data in one query and avoid the N+1 trap.
Quick Summary: Include loads related data. Select projects. Fluent API configures details.

