Entity Framework Core API Documentation

Entity Framework Core (EF Core) is a modern, cross-platform, open-source, and extensible version of the popular Microsoft Entity Framework data access technology.

EF Core allows .NET developers to work with a database using a model that corresponds to domain-specific objects they are familiar with, rather than the underlying database structure. It eliminates the need for most of the data-access code that developers traditionally need to write. EF Core supports LINQ queries against the model, which translate into database queries, and provides change tracking and concurrency control.

Key Features

Core Components

DbContext

The DbContext is the primary class used to interact with the database. It represents a session with the database and allows you to query and save data.


using Microsoft.EntityFrameworkCore;

public class MyDbContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

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

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

public class Post
{
    public int PostId { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
    public int BlogId { get; set; }
    public virtual Blog Blog { get; set; }
}
            

DbSet<TEntity>

A DbSet<TEntity> property on your DbContext represents a collection of entities of a particular type. You use it to query and save data for that entity.

Migrations

Migrations are a way to incrementally update your database schema to keep it in sync with your application's model. EF Core Migrations allow you to do this using code.

Getting Started

To get started with EF Core, you'll typically need to:

  1. Install the necessary EF Core NuGet packages.
  2. Define your model classes (entities).
  3. Create a DbContext class that derives from Microsoft.EntityFrameworkCore.DbContext.
  4. Configure the DbContext with connection string and the database provider.
  5. Generate and apply migrations to create or update your database schema.
  6. Query and save data using your DbContext instance.
Tip: For detailed installation and setup instructions, please refer to the Getting Started section.

Further Reading