Getting Started with Entity Framework
This guide will walk you through the essential steps to start using Entity Framework (EF) in your .NET applications. Entity Framework is a powerful Object-Relational Mapper (ORM) that enables developers to work with relational data as if they were using ordinary objects, eliminating much of the data-access code-shredding that developers need to write.
Prerequisites
Before you begin, ensure you have the following installed:
- .NET SDK (version 6.0 or later recommended)
- An IDE such as Visual Studio or VS Code
- Basic understanding of C# and object-oriented programming
Installation
Entity Framework can be installed via NuGet Package Manager. Open your project in your IDE and install the core EF package:
Using Package Manager Console:
Install-Package Microsoft.EntityFrameworkCore
Using .NET CLI:
dotnet add package Microsoft.EntityFrameworkCore
Depending on your database provider, you'll also need to install a specific EF Core provider package. For example, for SQL Server:
Using Package Manager Console (SQL Server):
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Using .NET CLI (SQL Server):
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Creating Your First Entity Framework Model
Entity Framework uses models to represent your database schema. You can define your models manually or generate them from an existing database.
1. Define Your Entity Classes
Create plain C# classes that represent your database tables. These are often referred to as Plain Old CLR Objects (POCOs).
Product.cs
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public DateTime ReleaseDate { get; set; }
}
2. Define Your DbContext Class
The DbContext
class is your primary gateway to interacting with your data. It represents a session around a database and allows you to query and save data.
MyDbContext.cs
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public DbSet Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Replace with your actual connection string
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=EFDemoDB;Trusted_Connection=True;");
}
}
OnConfiguring
is for demonstration purposes. In production, it's recommended to configure the connection string via dependency injection.
Database Migration
Entity Framework Migrations allow you to incrementally update your database schema as your models change. You first need to add the EF Core tools package:
Using Package Manager Console:
Install-Package Microsoft.EntityFrameworkCore.Tools
Using .NET CLI:
dotnet add package Microsoft.EntityFrameworkCore.Tools
Then, create your first migration:
Using Package Manager Console:
Add-Migration InitialCreate
Using .NET CLI:
dotnet ef migrations add InitialCreate
This will generate a C# script that EF uses to create your database. To apply the migration and create the database, run:
Using Package Manager Console:
Update-Database
Using .NET CLI:
dotnet ef database update
Performing Data Operations
Now that your database is set up, you can perform CRUD (Create, Read, Update, Delete) operations.
Adding a New Product
using var context = new MyDbContext();
var newProduct = new Product
{
Name = "Super Gadget",
Price = 99.99m,
ReleaseDate = DateTime.UtcNow
};
context.Products.Add(newProduct);
context.SaveChanges();
Console.WriteLine($"Added product with ID: {newProduct.ProductId}");
Querying Products
using var context = new MyDbContext();
var allProducts = context.Products.ToList();
Console.WriteLine($"Found {allProducts.Count} products:");
foreach (var product in allProducts)
{
Console.WriteLine($"- {product.Name} (${product.Price})");
}
var expensiveProducts = context.Products
.Where(p => p.Price > 50m)
.OrderBy(p => p.Name)
.ToList();
Console.WriteLine($"\nExpensive products:");
foreach (var product in expensiveProducts)
{
Console.WriteLine($"- {product.Name}");
}
Updating a Product
using var context = new MyDbContext();
var productToUpdate = context.Products.Find(1); // Assuming product with ID 1 exists
if (productToUpdate != null)
{
productToUpdate.Price = 109.99m;
context.SaveChanges();
Console.WriteLine($"Updated price for {productToUpdate.Name}");
}
Deleting a Product
using var context = new MyDbContext();
var productToDelete = context.Products.Find(2); // Assuming product with ID 2 exists
if (productToDelete != null)
{
context.Products.Remove(productToDelete);
context.SaveChanges();
Console.WriteLine($"Deleted product: {productToDelete.Name}");
}
DbContext
is properly disposed of, typically by using a using
statement or registering it with a dependency injection container.
Next Steps
This guide covers the basics of getting started with Entity Framework. To learn more, explore the following topics:
- Core EF Concepts: Learn about LINQ queries, change tracking, and relationships.
- Advanced Topics: Explore performance tuning, concurrency control, and more complex scenarios.