Introduction to Entity Framework
What is Entity Framework?
Entity Framework (EF) is a free, lightweight, extensible, and open-source, Object-Relational Mapper (ORM) for .NET. It enables developers to work with data as objects, rather than the underlying data stores. EF allows developers to interact with data using LINQ queries (Language-Integrated Query), which simplifies data access and manipulation.
EF translates your queries into SQL that can be sent to a relational database. EF can also map your database schema to your application's domain model. This abstraction layer helps developers be more productive by reducing the amount of boilerplate data access code they need to write.
Why Use Entity Framework?
- Productivity: Reduces the amount of repetitive data access code.
- Abstraction: Hides the complexities of the underlying database, allowing you to focus on your application logic.
- Maintainability: Code becomes easier to read, write, and maintain.
- Database Agnosticism: Supports multiple database providers (SQL Server, PostgreSQL, MySQL, SQLite, etc.) with minimal code changes.
- LINQ Integration: Leverage the power of LINQ for expressive and type-safe data querying.
- Developer Tools: Integrates seamlessly with Visual Studio for model design, database generation, and code scaffolding.
Core Concepts
Entity Framework is built around several key concepts:
1. DbContext
The DbContext
class is the primary gateway to interacting with data in Entity Framework. It represents a session with the database and allows you to query and save data. You typically create a derived context class and include DbSet<TEntity>
properties for each entity in your domain model.
using Microsoft.EntityFrameworkCore;
public class BloggingContext : 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=Blogging;Trusted_Connection=True;");
}
}
2. DbSet<TEntity>
A DbSet<TEntity>
property on your DbContext
instance represents a collection of all entities in the store for that type. You can think of it as a table in your database.
Example:
using var db = new BloggingContext();
var blogs = db.Blogs.ToList(); // Retrieves all blogs from the database
3. Entities
Entities are plain .NET objects (POCOs) that represent the data you are working with. They typically map directly to tables in your database.
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; }
}
4. Migrations
Migrations are a way to incrementally update your database schema to match your EF model. They allow you to evolve your database schema over time without losing existing data.
Getting Started
To start using Entity Framework, you'll need to add the appropriate EF Core NuGet packages to your project. The most common packages are:
Microsoft.EntityFrameworkCore
: The core EF Core library.Microsoft.EntityFrameworkCore.SqlServer
(or your specific database provider, e.g.,Npgsql.EntityFrameworkCore.PostgreSQL
): The provider for your database.Microsoft.EntityFrameworkCore.Tools
: For EF Core command-line tools (for migrations, scaffolding, etc.).
You can install these via the NuGet Package Manager in Visual Studio or using the .NET CLI:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
Once installed, you can define your DbContext
and entity classes, then use them to interact with your database.
For detailed guides and advanced topics, please refer to the official Entity Framework Core documentation.