Roadmap › Entity Framework (EF6 & EF Core) › Module: Relationships and Modelling
Lessons in this course (15)
5. One-to-one, one-to-many, many-to-many
Intermediate★ Must knowLesson 5 of 15
csharp
// One-to-many: Customer 1 — * Order
b.Entity<Order>().HasOne(o => o.Customer).WithMany(c => c.Orders)
.HasForeignKey(o => o.CustomerId).OnDelete(DeleteBehavior.Restrict);
// One-to-one: User 1 — 1 Profile (dependent has the FK)
b.Entity<User>().HasOne(u => u.Profile).WithOne(p => p.User).HasForeignKey<Profile>(p => p.UserId);
// Many-to-many (EF Core 5+): skip navigations, join table created automatically
public class Student { public int Id { get; set; } public List<Course> Courses { get; set; } = []; }
public class Course { public int Id { get; set; } public List<Student> Students { get; set; } = []; }
// Many-to-many with payload → explicit join entity
public class Enrollment { public int StudentId { get; set; } public int CourseId { get; set; } public DateTime EnrolledOn { get; set; } }Delete behaviours: Cascade (default for required relationships), Restrict/NoAction, SetNull, ClientSetNull. SQL Server rejects multiple cascade paths — use Restrict on one.