Entity Framework Core
Entity Framework Core (EF Core) is a modern, cross-platform, extensible data access framework for .NET. It is a rewrite of the popular Entity Framework 6 (EF6) with significant improvements and architectural changes. EF Core is designed to be lightweight, high-performance, and flexible, allowing developers to interact with databases using object-oriented programming principles.
Key Features and Benefits
- Cross-Platform: Runs on Windows, Linux, and macOS.
- Lightweight: Smaller footprint and reduced overhead compared to EF6.
- High Performance: Optimized for speed and efficiency.
- Extensible: Designed with extensibility in mind, allowing for custom providers and features.
- LINQ Integration: Seamlessly query your data using Language Integrated Query (LINQ).
- Migrations: Powerful tools for managing database schema changes over time.
- Multiple Database Support: Works with various database providers, including SQL Server, PostgreSQL, MySQL, SQLite, and more.
- Change Tracking: Efficiently tracks changes to entities for saving.
Core Concepts
Understanding these core concepts is crucial for effective use of EF Core:
-
DbContext: The primary class that represents a session with the database and allows you to query and save data. It's the gateway to your data.
public class MyDbContext : DbContext { public DbSet<Product> Products { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("YourConnectionString"); } }
- DbSet<TEntity>: Represents a collection of a given entity type in the context. You can think of it as a table in your database.
- Entities: Plain Old CLR Objects (POCOs) that represent the data you're working with.
- Model: The in-memory representation of your database schema, including entities, relationships, and constraints. EF Core can discover this model or you can configure it explicitly.
- Migrations: A feature that allows you to incrementally update your database schema to match your EF Core model without having to manually write SQL scripts.
Getting Started
To start using EF Core, you'll typically need to install the appropriate NuGet packages. The core package is Microsoft.EntityFrameworkCore
, and you'll need a provider package for your specific database.
For example, to use EF Core with SQL Server:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Refer to the Getting Started section for detailed instructions and examples.
Relationship to ADO.NET
While EF Core abstracts away much of the complexity of ADO.NET, it still builds upon it. Under the hood, EF Core uses ADO.NET to execute commands against the database. However, EF Core provides a much higher level of abstraction, allowing developers to work with objects rather than raw SQL and data readers.