How do you configure a One-to-Many relationship using Fluent API?
Updated Apr 28, 2026
Short answer
Use the HasOne/WithMany pattern in the OnModelCreating method to explicitly define the relationship and foreign keys.
Deep explanation
While EF Core can often infer relationships via conventions, Fluent API explicitly defines which entity 'HasOne' parent and 'WithMany' children. You can also configure the Foreign Key property and Cascade Delete behaviors here.
Real-world example
Linking a 'Department' to multiple 'Employees' and ensuring that if a Department is deleted, the Employees are handled correctly (e.g., set to null).
Common mistakes
- Configuring the relationship on both entities conflictingly, leading to model build errors.
Follow-up questions
- What does DeleteBehavior.Restrict do?