Friday, 1 November 2024

How do you perform basic CRUD operations using EF Core?

Entity Framework Core (EF Core) provides a straightforward way to perform basic CRUD (Create, Read, Update, Delete) operations on a database using a DbContext. Here’s how you can set up and perform each operation.

Setup

  1. Install EF Core: Ensure you have the EF Core package installed via NuGet:


    dotnet add package Microsoft.EntityFrameworkCore dotnet add package Microsoft.EntityFrameworkCore.SqlServer
  2. Create Model Classes: Define your model classes, for example, Product:


    public class Product { public int ProductId { get; set; } public string Name { get; set; } public decimal Price { get; set; } }
  3. Set up DbContext: Create a DbContext class to manage the entity models.


    public class AppDbContext : DbContext { public DbSet<Product> Products { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer("YourConnectionStringHere"); } }

CRUD Operations

1. Create Operation

To add new data, create an instance of the model, add it to the context, and call SaveChanges to persist it to the database.


using (var context = new AppDbContext()) { var product = new Product { Name = "Laptop", Price = 999.99m }; context.Products.Add(product); // Add the new product context.SaveChanges(); // Save changes to the database }

This will insert a new row into the Products table.

2. Read Operation

To read or retrieve data, use LINQ queries on the DbSet. You can retrieve single items or lists.


using (var context = new AppDbContext()) { // Retrieve all products var products = context.Products.ToList(); // Retrieve a single product by ID var singleProduct = context.Products.Find(1); // Fetches product with ID 1 // Retrieve products with specific criteria var expensiveProducts = context.Products .Where(p => p.Price > 500) .ToList(); }

Find works with the primary key and is optimized for quick lookups, while Where allows for more complex querying.

3. Update Operation

To update data, retrieve the entity, modify its properties, and call SaveChanges. EF Core tracks changes automatically.


using (var context = new AppDbContext()) { var product = context.Products.Find(1); // Fetch product with ID 1 if (product != null) { product.Price = 899.99m; // Modify the property context.SaveChanges(); // Save changes to update the database } }

When you call SaveChanges, EF Core will generate an SQL UPDATE command for the modified entity.

4. Delete Operation

To delete data, retrieve the entity you want to remove, call Remove, and then SaveChanges.


using (var context = new AppDbContext()) { var product = context.Products.Find(1); // Fetch product with ID 1 if (product != null) { context.Products.Remove(product); // Remove the product context.SaveChanges(); // Persist changes to the database } }

This will generate a DELETE SQL command to remove the specified row from the Products table.

Additional Tips

  • Asynchronous Methods: EF Core also provides asynchronous versions for all CRUD operations, such as AddAsync, FindAsync, ToListAsync, and SaveChangesAsync. These are useful for non-blocking operations in a web environment.


    var product = new Product { Name = "Tablet", Price = 299.99m }; await context.Products.AddAsync(product); await context.SaveChangesAsync();
  • Tracking: By default, EF Core tracks changes to entities. You can disable tracking on read operations for performance using AsNoTracking, which is useful when you’re only reading data and don’t intend to update it.


    var products = context.Products.AsNoTracking().ToList();

Summary Table

OperationMethodDescription
CreateAdd / AddAsyncAdds a new entity to the database.
ReadFind / Where / ToListRetrieves data from the database.
UpdateModify properties + SaveChangesUpdates the entity and saves changes to the database.
DeleteRemove + SaveChangesDeletes an entity from the database.

With these CRUD operations, you can manage basic data interactions in an EF Core-powered .NET Core application.

Share:

0 comments:

Post a Comment