ASP.NET Core → Entity Framework → Modeling Data

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.

1️⃣ Defining Entity Types

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; }
}

2️⃣ Configuring Relationships

One‑to‑Many (Blog ↔ Posts)

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);
Many‑to‑Many (Students ↔ Courses)

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.

3️⃣ Data Annotations vs Fluent API

Both approaches are valid; choose based on project size and maintainability.

Data Annotations
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; }
}
Fluent API
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)");
});

🛠️ Try It Live

Press the button to see the generated migration for the Blog model.

📚 Further Reading