.NET Documentation

Data Modeling in Entity Framework

Data modeling is a fundamental aspect of using Entity Framework (EF). It involves defining the structure of your data and how it relates to your application's objects. EF uses an Object-Relational Mapper (ORM) to bridge the gap between your object-oriented code and the relational database.

Core Concepts

EF primarily works with the concept of Entities and Entity Sets. An entity represents a single record or object within your data model, while an entity set represents a collection of entities of the same type.

Entities

Entities are typically represented by plain .NET classes (POCOs - Plain Old CLR Objects). These classes have properties that map to the columns in your database tables.


public class Product
{
    public int ProductId { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public ICollection<Product> Products { get; set; } = new List<Product>();
}
            

DbContext

The DbContext is the central class in EF. It represents a session with the database and is used to query and save data. It also manages the relationships between entities.


using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }
    public DbSet<Category> Categories { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Example connection string
        optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=MyDatabase;Trusted_Connection=True;");
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Fluent API configuration can go here
        modelBuilder.Entity<Category>()
            .HasMany(c => c.Products)
            .WithOne(p => p.Category); // Assuming Product has a CategoryId and Category navigation property
    }
}
            

Relationship Mapping

EF supports common relational database relationships:

These relationships are typically defined using navigation properties in your entity classes and can be further configured using the Fluent API within the DbContext's OnModelCreating method.

Entity Framework Data Modeling Relationships Diagram

Model Creation Strategies

There are two primary ways to create your EF model:

  1. Code-First: You define your .NET classes (entities) and EF generates the database schema based on these classes. This is the most common approach.
  2. Database-First: You have an existing database, and EF generates entity classes and a DbContext from that database.
  3. Model-First: You design your model visually using an Entity Designer, and EF generates both code and database schema.

Configuring the Model

You can configure your model in several ways: