Use navigation properties or the Fluent API to define the relationship.
modelBuilder.Entity()
.HasMany(b => b.Posts)
.WithOne(p => p.Blog)
.HasForeignKey(p => p.BlogId);
In this module you’ll learn how to define entity types, configure relationships, and choose between Data Annotations and the Fluent API to shape your database schema.
Entity types are represented by C# classes. By default EF Core maps public properties to columns.
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
public List Posts { get; set; }
}
Use navigation properties or the Fluent API to define the relationship.
modelBuilder.Entity()
.HasMany(b => b.Posts)
.WithOne(p => p.Blog)
.HasForeignKey(p => p.BlogId);
EF Core 5+ supports skip navigation for many‑to‑many.
public class Student
{
public int StudentId { get; set; }
public string Name { get; set; }
public ICollection Courses { get; set; }
}
public class Course
{
public int CourseId { get; set; }
public string Title { get; set; }
public ICollection Students { get; set; }
}
EF creates the join table automatically.
Both approaches are valid; choose based on project size and maintainability.
public class Product
{
[Key]
public int Id { get; set; }
[Required, MaxLength(100)]
public string Name { get; set; }
[Column(TypeName = "decimal(18,2)")]
public decimal Price { get; set; }
}
modelBuilder.Entity<Product>(entity =>
{
entity.HasKey(e => e.Id);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(100);
entity.Property(e => e.Price)
.HasColumnType("decimal(18,2)");
});
Press the button to see the generated migration for the Blog model.