Entity Framework Core: Mastering Basic CRUD Operations
Entity Framework Core (EF Core) is a powerful, open-source, cross-platform Object-Relational Mapper (ORM) for .NET. It allows developers to work with databases using .NET objects, abstracting away much of the underlying SQL. This module focuses on the fundamental Create, Read, Update, and Delete (CRUD) operations, essential for any data-driven application, with an eye towards Azure integration.
Understanding CRUD
CRUD is an acronym representing the four basic functions of persistent storage: Create, Read, Update, and Delete. In the context of EF Core, these operations translate to interacting with your database tables through your C# model classes.
CRUD Operation | EF Core Method | Database Action |
---|---|---|
Create | Add() and SaveChanges() | INSERT statement |
Read | Find(), FirstOrDefault(), Where(), ToList() | SELECT statement |
Update | Modify entity properties and SaveChanges() | UPDATE statement |
Delete | Remove() and SaveChanges() | DELETE statement |
Setting Up Your DbContext
Before performing CRUD operations, you need a
DbContext
DbSet
The DbContext represents a session with the database and provides access to your entities.
Performing Create Operations
To create a new record, you instantiate your entity class, populate its properties, and then add it to the appropriate
DbSet
DbContext
SaveChanges()
Adding a new record involves creating an entity instance and saving it.
Instantiate your model class, set its properties, add it to the DbSet
, and call SaveChanges()
.
Example:
var newProduct = new Product { Name = "Laptop", Price = 1200.00 };
_context.Products.Add(newProduct);
await _context.SaveChangesAsync();
This code snippet demonstrates how to create a new Product
entity and add it to the Products
DbSet before saving the changes asynchronously.
Performing Read Operations
Reading data involves querying your
DbContext
LINQ is used to query data from your DbContext.
Use LINQ methods like Find()
, FirstOrDefault()
, Where()
, and ToList()
to retrieve data.
To find a product by its ID:
var product = await _context.Products.FindAsync(productId);
To get all products with a price greater than 500:
var expensiveProducts = await _context.Products.Where(p => p.Price > 500).ToListAsync();
FindAsync
is optimized for primary key lookups, while Where
and ToListAsync
are used for more general filtering and retrieval.
Performing Update Operations
Updating an existing record involves retrieving the entity, modifying its properties, and then calling
SaveChanges()
Updates are made by modifying retrieved entities and saving changes.
Fetch the entity, change its properties, and call SaveChanges()
.
Example:
var productToUpdate = await _context.Products.FindAsync(productId);
if (productToUpdate != null)
{
productToUpdate.Price = 1300.00;
productToUpdate.Name = "Gaming Laptop";
await _context.SaveChangesAsync();
}
When SaveChanges()
is called, EF Core detects the modifications to productToUpdate
and generates an UPDATE
SQL statement.
Performing Delete Operations
To delete a record, you first retrieve the entity you wish to remove, then call the
Remove()
DbContext
DbSet
SaveChanges()
Deletion requires finding the entity and then removing it.
Retrieve the entity, use Remove()
on the DbSet, and call SaveChanges()
.
Example:
var productToDelete = await _context.Products.FindAsync(productId);
if (productToDelete != null)
{
_context.Products.Remove(productToDelete);
await _context.SaveChangesAsync();
}
This process marks the entity for deletion, and SaveChanges()
executes the corresponding DELETE
SQL command.
Asynchronous Operations and Azure Integration
For applications, especially those hosted on cloud platforms like Azure, it's crucial to use asynchronous methods (e.g.,
SaveChangesAsync()
ToListAsync()
FindAsync()
Always prefer asynchronous methods (async
/await
) when interacting with the database in .NET applications, particularly in web or cloud environments.
Summary of CRUD Operations
Mastering these basic CRUD operations with EF Core is fundamental for building data-driven applications. By leveraging LINQ and understanding the role of
DbContext
SaveChanges()
Learning Resources
The official Microsoft documentation provides a comprehensive guide to getting started with EF Core, including detailed explanations and examples of CRUD operations.
This resource delves deeper into how EF Core loads and saves data, covering various techniques for querying and manipulating entities.
A practical video tutorial demonstrating how to implement basic CRUD operations using EF Core in a C# application.
An in-depth blog post covering EF Core 7, including essential concepts and practical examples for data manipulation.
Learn how to perform CRUD operations within an ASP.NET Core application using Entity Framework Core 6.
The foundational guide to setting up and using EF Core, essential for understanding the context of CRUD operations.
Explains how to use LINQ to query data from your EF Core context, which is critical for read operations.
Understand the principles of asynchronous programming in C#, vital for efficient database interactions in modern applications.
Official documentation for Azure SQL Database, providing context for integrating EF Core with cloud data services.
Access the source code, track issues, and contribute to the development of Entity Framework Core. Useful for understanding its internals.