EF Core - Models

In Entity Framework Core (EF Core), models represent the structure of your data as classes that map to database tables. Defining models is a fundamental part of using EF Core, as it allows you to work with your data using objects instead of database tables and SQL. This tutorial explores how to define and configure models in EF Core.


1. Defining Models

Models in EF Core are defined as classes with properties that map to columns in a database table. Each model class represents an entity in your application.

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

In this example, the Product class represents a database table with columns for Id, Name, and Price.


2. Configuring Models

EF Core allows you to configure models using data annotations or the Fluent API to define how your classes map to database tables and columns.

Data Annotations Example:

        
            
public class Product
{
    [Key]
    public int Id { get; set; }

    [Required]
    [MaxLength(100)]
    public string Name { get; set; }

    [Range(0, 9999.99)]
    public decimal Price { get; set; }
}
        
    

Fluent API Example:

        
            
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Product>()
        .Property(p => p.Name)
        .IsRequired()
        .HasMaxLength(100);

    modelBuilder.Entity<Product>()
        .Property(p => p.Price)
        .HasColumnType("decimal(18,2)");
}
        
    

3. Relationships

EF Core supports various types of relationships between entities, including one-to-one, one-to-many, and many-to-many. You can define these relationships using navigation properties and configuration.

        
            
public class Order
{
    public int Id { get; set; }
    public DateTime OrderDate { get; set; }
    public ICollection<OrderItem> OrderItems { get; set; }
}

public class OrderItem
{
    public int Id { get; set; }
    public int OrderId { get; set; }
    public Order Order { get; set; }
    public string ProductName { get; set; }
    public decimal Price { get; set; }
}
        
    

In this example, the Order entity has a one-to-many relationship with the OrderItem entity, indicated by the OrderItems navigation property.


4. Best Practices for Model Design

Designing your models effectively is crucial for building scalable and maintainable applications. Here are some best practices to consider:


Summary

Models in EF Core are a critical aspect of your application's data layer, providing a way to represent and manipulate data as objects. By following best practices and using the configuration options available, you can design models that are efficient, scalable, and maintainable.