Entity Framework Core Overview

Entity Framework (EF) Core is a modern, cross-platform, open-source, and extensible version of the classic Entity Framework data access technology. It is a lightweight, extensible data access provider for .NET that supports a variety of SQL and NoSQL data stores. EF Core enables .NET developers to work with databases using a .NET object model.

What is Entity Framework Core?

EF Core provides a set of APIs and tools that allow you to:

Key Concepts

Understanding these core concepts will help you get started with EF Core:

DbContext

The DbContext class is the primary gateway to interacting with your data. It represents a session with the database and provides access to your entities. You'll typically create a class that inherits from DbContext and expose properties for each entity set.


using Microsoft.EntityFrameworkCore;

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

    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

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

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
            

DbSet<TEntity>

A DbSet<TEntity> property on your DbContext represents a collection of all entities of a given type in the store, or that can be queried from the store. It's the interface through which you query and save data for a particular entity type.

Migrations

Migrations are a feature of EF Core that allow you to evolve your database schema over time as your application's data model changes. You can add new tables, columns, constraints, or modify existing ones. EF Core generates the necessary SQL commands to apply these changes.

Note: Migrations are crucial for maintaining database consistency and enabling collaborative development.

Getting Started

To start using EF Core, you'll need to:

  1. Install the appropriate EF Core NuGet packages (e.g., Microsoft.EntityFrameworkCore.SqlServer for SQL Server).
  2. Define your DbContext and entity classes.
  3. Configure your DbContext in your application's service configuration (e.g., in Program.cs for ASP.NET Core).
  4. Create initial migrations and update your database.

For detailed steps, please refer to the Basic Operations tutorial.

Tip: Use the EF Core command-line tools or Package Manager Console for managing migrations.

Supported Data Stores

EF Core supports a growing list of data stores, including:

Each data store requires a specific EF Core provider package.

Next Steps

Now that you have a basic understanding of EF Core, you can explore other tutorials to dive deeper: