EF Core - Introduction

Entity Framework Core (EF Core) is a modern, open-source, and cross-platform object-relational mapper (ORM) for .NET. It simplifies data access by allowing developers to work with a database using .NET objects, eliminating much of the data-access code usually required.


What is EF Core?

EF Core is the successor to Entity Framework 6, redesigned to work seamlessly with .NET Core and newer versions of .NET. It is lightweight, extensible, and supports various databases, including SQL Server, SQLite, PostgreSQL, and MySQL.


Key Concepts

1. DbContext

The DbContext is the primary class for interacting with the database using EF Core. It manages database connections and is responsible for querying and saving data.

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

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer("YourConnectionStringHere");
    }
}
        
    

2. Entities

Entities are classes that map to database tables. Each instance of an entity represents a row within the table.

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

3. Configuration

EF Core provides two primary methods for configuring your model: using data annotations and the Fluent API. These configurations define how the entity classes map to the database schema.

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

Migrations

Migrations in EF Core allow you to incrementally apply schema changes to your database. They provide a way to keep your database schema in sync with your model classes as they evolve over time.

        
            
# Add a new migration
dotnet ef migrations add InitialCreate

# Apply the migration to the database
dotnet ef database update
        
    

Advanced Features

1. Querying Data

EF Core supports both LINQ and raw SQL queries. LINQ provides a strongly typed querying syntax that helps avoid runtime errors and provides IntelliSense support.

        
            
using (var context = new ApplicationDbContext())
{
    var products = context.Products
                          .Where(p => p.Price > 50)
                          .OrderBy(p => p.Name)
                          .ToList();
}
        
    

Raw SQL Example:

        
            
using (var context = new ApplicationDbContext())
{
    var expensiveProducts = context.Products
                                   .FromSqlRaw("SELECT * FROM Products WHERE Price > 50")
                                   .ToList();
}
        
    

2. Change Tracking

EF Core automatically tracks changes to entities retrieved from the database. When you call SaveChanges(), EF Core generates SQL commands to persist the changes.


3. Performance Optimization

EF Core offers various features for performance optimization, including eager loading, lazy loading, and explicit loading to control how related data is loaded.


Summary

EF Core is a powerful ORM that simplifies data access and management in .NET applications. From basic CRUD operations to advanced querying and performance optimization, EF Core provides a robust platform for building efficient and scalable applications. By understanding and leveraging its features, developers can create high-quality software solutions that meet modern application requirements.