Entity Framework Core Overview
Entity Framework Core (EF Core) is a modern, cross-platform, extensible data access framework for .NET. It is a lightweight, high-performance, and open-source version of the popular Entity Framework. EF Core allows developers to work with a database using .NET objects, abstracting away much of the low-level data access code.
Key Features of EF Core
- Cross-Platform Support: Runs on Windows, macOS, and Linux.
- Lightweight and Extensible: Designed for performance and allows for customization.
- LINQ to Entities: Enables querying the database using Language Integrated Query (LINQ).
- Database Providers: Supports a wide range of databases including SQL Server, PostgreSQL, MySQL, SQLite, Oracle, and Cosmos DB.
- Migrations: Manages database schema changes over time.
- Change Tracking: Automatically detects changes to entities.
- Concurrency Control: Provides mechanisms for handling concurrent data modifications.
- Performance Optimizations: Includes features like compiled queries and batching.
Core Concepts
DbContext
The DbContext
is the primary class that represents a session with the database and allows you to query and save data. It's your entry point to the EF Core world.
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("YourConnectionString");
}
}
DbSet<TEntity>
A DbSet<TEntity>
represents a collection of a given entity type in the context, which can be used to query and save data for that entity.
Entities
Plain Old CLR Objects (POCOs) that represent tables in your database. EF Core maps these objects to your database schema.
Data Access
EF Core provides several ways to interact with your data:
- Querying: Use LINQ to retrieve data.
- Adding: Use
_context.Add(entity)
. - Updating: Modify entity properties and call
_context.SaveChanges()
. - Deleting: Use
_context.Remove(entity)
.
Migrations
EF Core Migrations is a powerful feature that allows you to evolve your database schema in step with your object model. You can create new migrations manually or have EF Core generate them automatically based on changes to your DbContext
and entity models.
Common commands:
dotnet ef migrations add InitialCreate
dotnet ef database update
Scenarios
Code-First
In the Code-First approach, you define your entity classes and DbContext
first, and then EF Core generates the database schema based on your code.
Database-First
In the Database-First approach, you can scaffold EF Core model classes from an existing database. This is useful when you have a legacy database.
Next Steps
To get started with EF Core, explore the following topics: