Entity Framework Documentation
Entity Framework (EF) is a popular Object-Relational Mapper (ORM) for .NET developed by Microsoft. It enables developers to work with relational databases using .NET objects, eliminating the need for most of the data-access code they typically need to write. EF supports LINQ queries, allowing you to write database queries in C# or VB.NET.
Getting Started with Entity Framework
To start using Entity Framework in your .NET project, you'll need to install the appropriate NuGet packages. The core package is Microsoft.EntityFrameworkCore. Depending on your database provider, you'll also need to install a specific provider package, such as:
Microsoft.EntityFrameworkCore.SqlServerfor SQL ServerMicrosoft.EntityFrameworkCore.SQLitefor SQLiteMicrosoft.EntityFrameworkCore.Cosmosfor Azure Cosmos DBNpgsql.EntityFrameworkCore.PostgreSQLfor PostgreSQL
Once installed, you define your database context and entity classes, and EF handles the rest.
Core Concepts
DbContext
The DbContext class is the primary class used when interacting with the database. It represents a session with the database and is a gateway to querying and saving data. It provides access to collections of entities, which can be queried.
public class MyDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public DbSet<Category> Categories { get; set; }
// Constructor for configuration (e.g., connection string)
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("YourConnectionString");
}
}
Entity Classes
Entity classes represent the tables in your database. They are simple POCOs (Plain Old CLR Objects) that map to database tables. EF uses conventions to map these classes to your database schema.
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int CategoryId { get; set; }
public Category Category { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string Name { get; set; }
public ICollection<Product> Products { get; set; }
}
DbContextProvider (Note: This term might be less common in EF Core, often configuration is handled in OnConfiguring or dependency injection.)
In modern EF Core, configuration is typically done via OnConfiguring or by registering services in your application's dependency injection container. This allows for flexible configuration of the database provider and other options.
Migrations
Entity Framework Migrations allow you to incrementally update your database schema as your model changes. They allow you to represent changes to your database schema as code. You can enable migrations and then add new migrations as you modify your entity classes or DbContext.
To add a migration using the .NET CLI:
dotnet ef migrations add InitialCreate
To apply migrations to the database:
dotnet ef database update
Querying Data
You can query data from your database using LINQ to Entities. The DbSet<TEntity> property on your DbContext represents the collection of all entities in the store for that type. You can use LINQ methods like Where, Select, OrderBy, etc.
using (var context = new MyDbContext())
{
var products = context.Products
.Where(p => p.Price > 50)
.OrderBy(p => p.Name)
.ToList();
foreach (var product in products)
{
Console.WriteLine($"{product.Name} - {product.Price:C}");
}
}
Saving Data
To save data, you can add new entities, mark existing entities for modification, or mark entities for deletion. The DbContext tracks these changes.
using (var context = new MyDbContext())
{
// Adding a new entity
var newProduct = new Product { Name = "New Gadget", Price = 199.99, CategoryId = 1 };
context.Products.Add(newProduct);
// Modifying an existing entity (assuming it's already tracked or loaded)
var existingProduct = context.Products.Find(1);
if (existingProduct != null)
{
existingProduct.Price = 55.00m;
}
// Deleting an entity
var productToDelete = context.Products.Find(2);
if (productToDelete != null)
{
context.Products.Remove(productToDelete);
}
context.SaveChanges(); // Persists all changes to the database
}
Advanced Topics
Entity Framework also supports advanced features like:
- Database-first, model-first, and code-first approaches
- Relationships and navigation properties
- Transactions
- Concurrency control
- Raw SQL queries
- Entity splitting and table sharing
- Change tracking and lazy loading
API Reference
For a comprehensive list of classes, methods, and properties, please refer to the official Entity Framework Core API documentation: