EF Core models relationships—one-to-many, many-to-many, one-to-one—with navigation properties and foreign keys, similar to Django ForeignKey and ManyToManyField.
One-to-many
public class Order {
public int Id { get; set; }
public List<OrderLine> Lines { get; set; } = new();
}
public class OrderLine {
public int Id { get; set; }
public int OrderId { get; set; }
public Order Order { get; set; } = null!;
}
Eager loading
var order = await _db.Orders
.Include(o => o.Lines)
.FirstAsync(o => o.Id == id);
Fluent API
Configure delete behaviors, composite keys, and indexes in OnModelCreating when conventions aren't enough.
Important interview questions and answers
- Q: Include vs projection?
A: Include loads full related entities; Select projects only needed fields—often faster for APIs. - Q: Cascade delete?
A: Deleting parent may delete children—configure intentionally to avoid accidental data loss.
Self-check
- What property holds the FK on the many side?
- How do you load Order with Lines in one query?
Tip: N+1 queries happen when you loop entities and lazy-load navigation properties—use Include or project with Select in one query.