EF Core Relationships
In EF Core, you can define relationships between entities to reflect real-world associations. These include one-to-one, one-to-many, and many-to-many relationships.
One-to-Many Relationship
Example: One Category can have many Products
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
public List<Product> Products { get; set; } // Navigation property
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public int CategoryId { get; set; } // Foreign key
public Category Category { get; set; } // Navigation property
}
One-to-One Relationship
Example: Each User has one Profile
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public Profile Profile { get; set; }
}
public class Profile
{
public int Id { get; set; }
public string Bio { get; set; }
public int UserId { get; set; }
public User User { get; set; }
}
Many-to-Many Relationship
Example: Students and Courses — a student can enroll in many courses and a course can have many students.
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public List<Course> Courses { get; set; }
}
public class Course
{
public int Id { get; set; }
public string Title { get; set; }
public List<Student> Students { get; set; }
}
EF Core 5+ automatically creates a join table for many-to-many relationships.
Fluent API Configuration (Optional)
Use OnModelCreating
to configure relationships explicitly:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOne(u => u.Profile)
.WithOne(p => p.User)
.HasForeignKey<Profile>(p => p.UserId);
}
Querying with Navigation Properties
Use Include()
to load related entities:
var category = context.Categories
.Include(c => c.Products)
.FirstOrDefault(c => c.Id == 1);
EF Core makes it easy to model real-world relationships between entities. In the next lesson, we’ll learn how to query these relationships efficiently using LINQ and projection.