LibraryBasic CRUD Operations

Basic CRUD Operations

Learn about Basic CRUD Operations as part of C# .NET Development and Azure Integration

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 OperationEF Core MethodDatabase Action
CreateAdd() and SaveChanges()INSERT statement
ReadFind(), FirstOrDefault(), Where(), ToList()SELECT statement
UpdateModify entity properties and SaveChanges()UPDATE statement
DeleteRemove() and SaveChanges()DELETE statement

Setting Up Your DbContext

Before performing CRUD operations, you need a

code
DbContext
. This class represents a session with the database and allows you to query and save data. It typically includes
code
DbSet
properties for each entity in your model.

What is the primary role of the DbContext in EF Core?

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

code
DbSet
in your
code
DbContext
. Finally, call
code
SaveChanges()
to persist the changes to the database.

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

code
DbContext
. EF Core provides LINQ (Language Integrated Query) to perform these queries. You can retrieve single entities, collections of entities, and filter them based on various criteria.

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

code
SaveChanges()
. EF Core tracks changes to entities that are already being tracked by the context.

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

code
Remove()
method on the
code
DbContext
's
code
DbSet
, and finally call
code
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.,

code
SaveChangesAsync()
,
code
ToListAsync()
,
code
FindAsync()
). This prevents blocking the main thread and improves application responsiveness and scalability. EF Core seamlessly integrates with Azure SQL Database, Cosmos DB, and other Azure data services.

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

code
DbContext
and
code
SaveChanges()
, you can efficiently manage data. Remember to utilize asynchronous patterns for optimal performance, especially when integrating with cloud services like Azure.

Learning Resources

EF Core Basics: CRUD Operations - Microsoft Learn(documentation)

The official Microsoft documentation provides a comprehensive guide to getting started with EF Core, including detailed explanations and examples of CRUD operations.

Entity Framework Core: Working with Data - Microsoft Learn(documentation)

This resource delves deeper into how EF Core loads and saves data, covering various techniques for querying and manipulating entities.

CRUD Operations with Entity Framework Core - YouTube Tutorial(video)

A practical video tutorial demonstrating how to implement basic CRUD operations using EF Core in a C# application.

Entity Framework Core 7: A Complete Guide - Code-Maze(blog)

An in-depth blog post covering EF Core 7, including essential concepts and practical examples for data manipulation.

EF Core 6: CRUD Operations with ASP.NET Core - YouTube(video)

Learn how to perform CRUD operations within an ASP.NET Core application using Entity Framework Core 6.

Entity Framework Core - Getting Started - Official Docs(documentation)

The foundational guide to setting up and using EF Core, essential for understanding the context of CRUD operations.

LINQ to Entities: Querying Data - Microsoft Learn(documentation)

Explains how to use LINQ to query data from your EF Core context, which is critical for read operations.

Asynchronous Programming with Async and Await in C# - Microsoft Learn(documentation)

Understand the principles of asynchronous programming in C#, vital for efficient database interactions in modern applications.

Azure SQL Database Documentation - Microsoft Learn(documentation)

Official documentation for Azure SQL Database, providing context for integrating EF Core with cloud data services.

Entity Framework Core - GitHub Repository(documentation)

Access the source code, track issues, and contribute to the development of Entity Framework Core. Useful for understanding its internals.