How to configure a one-to-many relationship?
Fluent API:
modelBuilder.Entity<Blog>()
.HasMany(b => b.Posts)
.WithOne(p => p.Blog)
.HasForeignKey(p => p.BlogId);
Data annotations:
public class Post
public int BlogId { get; set; }
[ForeignKey("BlogId")]
public Blog Blog { get; set; }
- A foreign key exists in the many-side entity (Post).
- EF infers this relationship from navigation + FK.