This learn path guides you through using Entity Framework Core (EF Core) to interact with your database in ASP.NET Core applications. EF Core is a modern object-relational mapper (ORM) that enables .NET developers to work with databases using domain-specific objects and LINQ.
Entity Framework Core is a lightweight, extensible data access technology that enables the development of functional domain models using a relational database. It allows you to query a database and work with the results as strongly typed .NET objects.
This section covers the initial setup of EF Core in your ASP.NET Core project, including installing necessary NuGet packages and configuring the DbContext.
You'll need to install the appropriate EF Core provider for your database (e.g., SQL Server, PostgreSQL, SQLite).
dotnet add package Microsoft.EntityFrameworkCore.SqlServerFor SQL Server support. Replace SqlServer with your chosen database provider.
Registering your DbContext in the Startup.cs (or equivalent) file and configuring the database connection string.
// In Startup.cs or Program.cs
services.AddDbContext<MyDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Define your data models as Plain Old CLR Objects (POCOs) and use EF Core Migrations to manage your database schema changes.
Create classes that represent your database tables.
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Use migrations to create and update your database schema based on your entity models.
dotnet ef migrations add InitialCreatedotnet ef database update
Learn how to retrieve data from your database using Language Integrated Query (LINQ).
var products = await _context.Products
.Where(p => p.Price > 10.00m)
.OrderBy(p => p.Name)
.ToListAsync();
var productsWithCategory = await _context.Products
.Include(p => p.Category)
.ToListAsync();
Understand how to add, update, and delete data in your database.
var newProduct = new Product { Name = "New Gadget", Price = 49.99m };
_context.Products.Add(newProduct);
await _context.SaveChangesAsync();
var productToUpdate = await _context.Products.FindAsync(productId);
if (productToUpdate != null)
{
productToUpdate.Price = 55.00m;
await _context.SaveChangesAsync();
}
var productToDelete = await _context.Products.FindAsync(productId);
if (productToDelete != null)
{
_context.Products.Remove(productToDelete);
await _context.SaveChangesAsync();
}
Explore more advanced features and best practices for using EF Core.