MSDN Documentation

Entity Framework Core APIs

Entity Framework Core (EF Core) is a modern, cross-platform, and open-source version of the popular Microsoft data access technology, Entity Framework. It allows developers to work with a database using .NET objects that represent the data, rather than directly interacting with database tables and columns. This document outlines the core APIs and concepts you'll use when working with EF Core.

Key Concepts

Core API Components

1. DbContext

The DbContext class is the heart of EF Core. You typically derive from it to create your own context class, configuring it to interact with your specific database.

Configuration

You can configure your DbContext using:

  • Data Annotations: Attributes applied directly to your entity classes (e.g., [Table("Products")]).
  • Fluent API: A programmatic way to configure your model using the OnModelCreating method in your DbContext. This is generally preferred for complex configurations.

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

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

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Product>().HasKey(p => p.Id);
        modelBuilder.Entity<Product>().Property(p => p.Name).IsRequired().HasMaxLength(100);
        modelBuilder.Entity<Product>().HasOne(p => p.Category)
                                       .WithMany(c => c.Products)
                                       .HasForeignKey(p => p.CategoryId);
    }
}
                    
Common Operations

Adding an entity:


var product = new Product { Name = "Example Product", Price = 19.99m };
context.Products.Add(product);
context.SaveChanges();
                    

Querying entities:


var allProducts = context.Products.ToList();
var expensiveProducts = context.Products.Where(p => p.Price > 50).ToList();
                    

Updating an entity:


var productToUpdate = context.Products.Find(1);
if (productToUpdate != null)
{
    productToUpdate.Price = 24.99m;
    context.SaveChanges();
}
                    

Deleting an entity:


var productToDelete = context.Products.Find(2);
if (productToDelete != null)
{
    context.Products.Remove(productToDelete);
    context.SaveChanges();
}
                    

2. DbSet<TEntity>

DbSet<TEntity> provides methods for querying and interacting with a collection of entities of a specific type.

  • LINQ Queries: You can use Language Integrated Query (LINQ) to retrieve data from your DbSet. EF Core translates these LINQ queries into SQL.
  • Add, Update, Remove: Methods like Add(), Update(), and Remove() are used to track changes to entities.
  • Find(): Efficiently retrieves an entity by its primary key.

See DbContext examples above for practical usage.

3. Migrations

EF Core Migrations allow you to manage database schema changes:

  • Enable Migrations: Run dotnet ef migrations add InitialCreate in your project directory.
  • Apply Migrations: Run dotnet ef database update to apply pending migrations to your database.
  • Generate SQL: Use dotnet ef migrations script to generate SQL scripts for review or deployment.

Resources