Entity Framework
Entity Framework (EF) is an open-source, object-relational mapper (ORM) for .NET. It enables developers to work with databases using .NET objects, eliminating the need for most of the data-access code that developers traditionally need to write. EF can also be used to create and manage database schemas.
What is Entity Framework?
Entity Framework allows you to query relational data in a type-safe way. You can think of your database as a collection of objects, and EF helps you to interact with these objects using LINQ (Language Integrated Query) or query syntax.
Key Concepts
- DbContext: Represents a session with the database and allows you to query and save data.
- DbSet: Represents a collection of entities of a given type in the context.
- Entities: Plain Old CLR Objects (POCOs) that represent the data in your database tables.
- Migrations: A feature that allows you to evolve your database schema over time as your application's model changes.
Getting Started
To get started with Entity Framework, you typically need to install the appropriate NuGet packages:
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer # Or your specific database provider
dotnet add package Microsoft.EntityFrameworkCore.Tools
Example: Basic Usage
Creating a DbContext
Define your entity classes and then create a derived DbContext
class:
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ApplicationDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
// Optional: Configure database connection, etc.
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("YourConnectionStringHere");
}
}
}
Querying Data
Use LINQ to query your entities:
using (var context = new ApplicationDbContext(new DbContextOptions<ApplicationDbContext>()))
{
var firstProduct = context.Products.FirstOrDefault();
if (firstProduct != null)
{
Console.WriteLine($"First product: {firstProduct.Name}");
}
var expensiveProducts = context.Products.Where(p => p.Price > 100).ToList();
foreach (var product in expensiveProducts)
{
Console.WriteLine($"- {product.Name}");
}
}
Saving Data
Add, update, or remove entities and then call SaveChanges()
:
using (var context = new ApplicationDbContext(new DbContextOptions<ApplicationDbContext>()))
{
var newProduct = new Product { Name = "New Gadget", Price = 49.99m };
context.Products.Add(newProduct);
await context.SaveChangesAsync();
var productToUpdate = await context.Products.FindAsync(newProduct.ProductId);
if (productToUpdate != null)
{
productToUpdate.Price = 54.99m;
await context.SaveChangesAsync();
}
var productToRemove = await context.Products.FindAsync(newProduct.ProductId);
if (productToRemove != null)
{
context.Products.Remove(productToRemove);
await context.SaveChangesAsync();
}
}