CRUD stands for Create, Read, Update, and Delete, which are the basic operations for interacting with a database. Entity Framework Core simplifies these operations by allowing developers to use .NET objects to manipulate database records.
Ensure you have a DbContext and models set up for your application. For this example, let’s assume
we have a Customer
model and a configured ApplicationDbContext
.
// Models/Customer.cs
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string City { get; set; }
}
// DbContext/ApplicationDbContext.cs
public class ApplicationDbContext : DbContext
{
public DbSet<Customer> Customers { get; set; }
}
Here are the basic CRUD operations demonstrated step-by-step:
// Adding a new customer
using (var context = new ApplicationDbContext())
{
var customer = new Customer
{
Name = "John Doe",
Email = "john.doe@example.com",
City = "New York"
};
context.Customers.Add(customer);
context.SaveChanges();
}
This code creates a new customer record in the database.
// Fetching all customers
using (var context = new ApplicationDbContext())
{
var customers = context.Customers.ToList();
}
This query retrieves all records from the Customers
table.
// Updating a customer's information
using (var context = new ApplicationDbContext())
{
var customer = context.Customers.FirstOrDefault(c => c.Id == 1);
if (customer != null)
{
customer.City = "Los Angeles";
context.SaveChanges();
}
}
The FirstOrDefault
method fetches the specific record, which is then updated and saved
back to the database.
// Deleting a customer
using (var context = new ApplicationDbContext())
{
var customer = context.Customers.FirstOrDefault(c => c.Id == 1);
if (customer != null)
{
context.Customers.Remove(customer);
context.SaveChanges();
}
}
This code removes the customer with Id = 1
from the database.