Entity Framework Core Interview Question #36

How do you configure relationships with the Fluent API?

Relationships, Navigation Properties & Loading Data Junior Beginner

Quick Interview Answer

Relationship configuration typically starts with HasOne or HasMany and continues with WithOne or WithMany. HasForeignKey can explicitly identify the dependent foreign-key property.

Detailed Explanation

Relationship configuration typically starts with HasOne or HasMany and continues with WithOne or WithMany. HasForeignKey can explicitly identify the dependent foreign-key property.

The Fluent API can also configure requiredness, delete behavior, constraint names, and join-table details.

Explicit configuration is valuable when conventions could be ambiguous or when the database schema has specific requirements.

Code Example

modelBuilder.Entity<Order>()
    .HasOne(o => o.Customer)
    .WithMany(c => c.Orders)
    .HasForeignKey(o => o.CustomerId)
    .OnDelete(DeleteBehavior.Restrict);