Defining Models

In Entity Framework (EF), a model represents the structure of your data. It's a collection of entities, their properties, and the relationships between them. Defining your model is a crucial step in using EF to interact with your database. EF provides several ways to define your model, catering to different development styles.

Code-First Approach

The Code-First approach allows you to define your model using C# or VB.NET classes. EF then infers the database schema from these classes. This is often the preferred approach for new projects where you want to start with your domain logic.

Entity Classes

An entity class typically represents a table in your database. Each public property of the class corresponds to a column in that table.


public class Product
{
    public int ProductId { get; set; } // Primary key
    public string Name { get; set; }
    public decimal Price { get; set; }
    public int CategoryId { get; set; } // Foreign key
    public Category Category { get; set; } // Navigation property
}

public class Category
{
    public int CategoryId { get; set; } // Primary key
    public string Name { get; set; }
    public ICollection<Product> Products { get; set; } // Navigation property
}
                

DbContext

The DbContext class is the primary gateway to interact with your EF model and the database. It represents a session with the database and can be used to query and save data.


using Microsoft.EntityFrameworkCore;

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

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Further model configuration can be done here if needed
        modelBuilder.Entity<Product>()
            .HasOne(p => p.Category)
            .WithMany(c => c.Products)
            .HasForeignKey(p => p.CategoryId);
    }
}
                
Note: By convention, EF recognizes properties named Id or ClassNameId as primary keys. It also infers relationships based on the presence of navigation properties and foreign key properties.

Database-First Approach

The Database-First approach starts with an existing database. EF can generate model classes and a DbContext from your database schema. This is useful when you have a legacy database you need to work with.

You can use the EF Core Power Tools (available as a Visual Studio extension) or the EF Core command-line tools to scaffold your model from an existing database.

Model Building API

EF Core's fluent API, configured within the OnModelCreating method of your DbContext, provides a powerful way to configure your model beyond conventions. This allows fine-grained control over table names, column types, constraints, relationships, and more.

Example Configurations:

  • Table and Column Naming:
  • 
    modelBuilder.Entity<Product>().ToTable("ProductsTable");
    modelBuilder.Entity<Product>().Property(p => p.Price).HasColumnName("UnitPrice");
                        
  • Data Types:
  • 
    modelBuilder.Entity<Product>().Property(p => p.Name).HasMaxLength(100);
    modelBuilder.Entity<Product>().Property(p => p.Price).HasColumnType("decimal(18, 2)");
                        
  • Required Properties:
  • 
    modelBuilder.Entity<Product>().Property(p => p.Name).IsRequired();
                        
  • Relationships: (Already shown in DbContext example)
Tip: For complex models or specific requirements, the fluent API offers extensive customization options that can be crucial for optimizing database interactions.

Key Concepts in Model Definition:

  • Entities: Plain old CLR objects (POCOs) representing data.
  • Properties: Represent attributes of entities (columns in database tables).
  • DbContext: Manages entity instances and the interaction with the database.
  • DbSet<TEntity>: Represents a collection of entities in the DbContext, typically mapping to a database table.
  • Relationships: Define how entities are connected (one-to-one, one-to-many, many-to-many).
  • Primary Keys: Uniquely identify entities.
  • Foreign Keys: Link related entities.
  • Navigation Properties: Allow easy traversal between related entities.
Important: Choose the modeling approach that best suits your project. For new applications, Code-First is generally recommended for its developer productivity.

Understanding how to define your models effectively is fundamental to leveraging the power of Entity Framework for .NET data access.