CRUD operations (Create, Read, Update, Delete) are fundamental operations for managing data in web applications. In ASP.NET Core, you can implement these operations using Entity Framework Core (EF Core) to interact with a database. This guide will walk you through the steps to implement CRUD operations in an ASP.NET Core application.

Step 1: Set Up the Project

Start by creating a new ASP.NET Core Web API project. You can do this using the .NET CLI:

        
dotnet new webapi -n CrudExample
cd CrudExample

Step 2: Install Required Packages

Install the necessary NuGet packages for Entity Framework Core. For example, to use EF Core with SQL Server, run the following commands:

        
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

Step 3: Create the Model Class

Define a model class that represents the data structure. Below is an example of a simple Product model.

        
using System.ComponentModel.DataAnnotations;

public class Product
{
public int Id { get; set; }

[Required(ErrorMessage = "Product name is required.")]
[StringLength(100, ErrorMessage = "Product name cannot exceed 100 characters.")]
public string Name { get; set; }

[Range(0.01, 10000.00, ErrorMessage = "Price must be between 0.01 and 10,000.00.")]
public decimal Price { get; set; }
}

Step 4: Create the Database Context

Create a database context class that derives from DbContext. This class will manage the entity objects during runtime and provide access to the database.

        
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}

public DbSet<Product> Products { get; set; } // DbSet for Product entity
}

Step 5: Configure the Database Connection

In the Startup class, configure the database context and specify the connection string.

        
using Microsoft.EntityFrameworkCore;

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer("YourConnectionStringHere")); // Replace with your connection string

services.AddControllers(); // Add services for controllers
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); // Map attribute-routed controllers
});
}
}

Step 6: Create the Products Controller

Create a controller to handle the CRUD operations. Below is an example of a ProductsController that implements the CRUD operations.

        
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly ApplicationDbContext _context;

public ProductsController(ApplicationDbContext context)
{
_context = context;
}

// GET: api/products
[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _context.Products.ToListAsync(); // Read all products
}

// GET: api/products/5
[HttpGet("{id}")]
public async Task<ActionResult<Product>> Get Product(int id)
{
var product = await _context.Products.FindAsync(id); // Read a specific product
if (product == null)
{
return NotFound(); // Return 404 if not found
}
return product;
}

// POST: api/products
[HttpPost]
public async Task<ActionResult<Product>> PostProduct(Product product)
{
_context.Products.Add(product); // Create a new product
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product); // Return 201 with location
}

// PUT: api/products/5
[HttpPut("{id}")]
public async Task<IActionResult> PutProduct(int id, Product product)
{
if (id != product.Id)
{
return BadRequest(); // Return 400 if IDs do not match
}

_context.Entry(product).State = EntityState.Modified; // Update the product
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(id))
{
return NotFound(); // Return 404 if not found
}
else
{
throw; // Rethrow the exception
}
}
return NoContent(); // Return 204 on success
}

// DELETE: api/products/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProduct(int id)
{
var product = await _context.Products.FindAsync(id); // Find the product
if (product == null)
{
return NotFound(); // Return 404 if not found
}

_context.Products.Remove(product); // Delete the product
await _context.SaveChangesAsync();
return NoContent(); // Return 204 on success
}

private bool ProductExists(int id)
{
return _context.Products.Any(e => e.Id == id); // Check if product exists
}
}

Conclusion

Implementing CRUD operations in ASP.NET Core is straightforward with the help of Entity Framework Core. By following the steps outlined above, you can create a fully functional API that allows you to manage your data effectively. This setup provides a solid foundation for building more complex applications that require data management capabilities.