Performing CRUD Operations with EF Core
This guide demonstrates how to perform the fundamental Create, Read, Update, and Delete (CRUD) operations using Entity Framework Core in a .NET Core application. EF Core simplifies data access by allowing you to work with your database using .NET objects.
1. Setting Up the DbContext and Models
First, ensure you have your data models defined and a DbContext
that represents your database session.
Model Definition (e.g., Product.cs)
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int Stock { get; set; }
}
DbContext Definition (e.g., AppDbContext.cs)
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options)
: base(options)
{
}
public DbSet<Product> Products { get; set; }
// Configure your database provider and connection string in Startup.cs or appsettings.json
}
2. Creating (Adding) a New Record
To add a new entity, create an instance of your model, attach it to the DbContext
, and save the changes.
C# Code
using (var context = new AppDbContext(/* options */))
{
var newProduct = new Product
{
Name = "Wireless Mouse",
Price = 25.99m,
Stock = 150
};
context.Products.Add(newProduct); // Or context.Add(newProduct);
await context.SaveChangesAsync(); // Saves changes to the database
Console.WriteLine($"Product added with ID: {newProduct.ProductId}");
}
3. Reading (Querying) Records
You can query records using LINQ to query your DbSet
.
Get All Products
using (var context = new AppDbContext(/* options */))
{
var allProducts = await context.Products.ToListAsync();
foreach (var product in allProducts)
{
Console.WriteLine($"- {product.Name} (Price: {product.Price:C}, Stock: {product.Stock})");
}
}
Get a Specific Product by ID
using (var context = new AppDbContext(/* options */))
{
int productIdToFind = 1; // Example ID
var product = await context.Products.FindAsync(productIdToFind);
if (product != null)
{
Console.WriteLine($"Found Product: {product.Name}");
}
else
{
Console.WriteLine($"Product with ID {productIdToFind} not found.");
}
}
Querying with Filters
using (var context = new AppDbContext(/* options */))
{
// Find products with stock less than 50
var lowStockProducts = await context.Products
.Where(p => p.Stock < 50)
.ToListAsync();
Console.WriteLine("Low Stock Products:");
foreach (var product in lowStockProducts)
{
Console.WriteLine($"- {product.Name} (Stock: {product.Stock})");
}
}
4. Updating a Record
To update an existing entity, fetch it, modify its properties, and then save the changes.
C# Code
using (var context = new AppDbContext(/* options */))
{
int productIdToUpdate = 1; // Example ID
var productToUpdate = await context.Products.FindAsync(productIdToUpdate);
if (productToUpdate != null)
{
productToUpdate.Price = 29.95m; // Update price
productToUpdate.Stock += 20; // Update stock
// EF Core tracks changes to entities that are being tracked.
// No need to explicitly call context.Update(productToUpdate) if it's already tracked.
await context.SaveChangesAsync();
Console.WriteLine($"Product '{productToUpdate.Name}' updated.");
}
else
{
Console.WriteLine($"Product with ID {productIdToUpdate} not found for update.");
}
}
5. Deleting a Record
To delete an entity, fetch it, then mark it for deletion and save the changes.
C# Code
using (var context = new AppDbContext(/* options */))
{
int productIdToDelete = 2; // Example ID
var productToDelete = await context.Products.FindAsync(productIdToDelete);
if (productToDelete != null)
{
context.Products.Remove(productToDelete); // Or context.Remove(productToDelete);
await context.SaveChangesAsync();
Console.WriteLine($"Product '{productToDelete.Name}' deleted.");
}
else
{
Console.WriteLine($"Product with ID {productIdToDelete} not found for deletion.");
}
}