What are foreign keys and primary keys?
How to define them via
annotations & Fluent API?
- Primary Key (PK): Unique identifier of a record.
- Foreign Key (FK): A field that references a PK in another table.
Data Annotations:
[Key]
public int Id { get; set; }
[ForeignKey("Blog")]
public int BlogId { get; set; }
Fluent API:
modelBuilder.Entity<Post>()
.HasKey(p => p.Id);
modelBuilder.Entity<Post>()
.HasOne(p => p.Blog)
.WithMany(b => b.Posts)
.HasForeignKey(p => p.BlogId);