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
- LINQ Queries: Write database queries using Language Integrated Query (LINQ) in C# or F#.
- Change Tracking: EF Core automatically tracks changes to entities.
- Database Providers: Support for various database systems including SQL Server, PostgreSQL, MySQL, SQLite, and more.
- Migrations: Manage database schema changes over time without losing data.
- Performance Optimizations: Built with performance in mind, including features like compiled queries and efficient change tracking.
- Cross-Platform: Runs on Windows, macOS, and Linux.
- Extensibility: Highly customizable and extensible to meet specific application needs.
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:
- Install the necessary EF Core NuGet packages.
- Define your model classes (entities).
- Create a
DbContext
class that derives fromMicrosoft.EntityFrameworkCore.DbContext
. - Configure the
DbContext
with connection string and the database provider. - Generate and apply migrations to create or update your database schema.
- Query and save data using your
DbContext
instance.