• Home
  • /
  • Blogs
  • /
  • How To Implement Crud Operations In A Net Core Web Api

How to Implement CRUD Operations in a .NET Core Web API

How to Implement CRUD Operations in a .NET Core Web API

When building web applications, one of the fundamental tasks is to handle CRUD operations: Create, Read, Update, and Delete data. In a .NET Core Web API, performing these operations allows you to interact with your data in a structured and organized way.

In this blog post, we’ll walk through the steps of setting up a .NET Core Web API with Entity Framework Core to handle CRUD operations for a basic Product model.


Step 1: Setting Up Your .NET Core Web API Project

Before we begin implementing CRUD operations, you need to create a new ASP.NET Core Web API project.

  1. Open Visual Studio.
  2. Click on Create a new project.
  3. Choose the ASP.NET Core Web API template.
  4. Name your project, for example, CrudApiDemo, and select .NET Core and the latest version of ASP.NET Core.
  5. Click Create to set up your project.

Now, you have an empty Web API project, and we’re ready to start implementing our CRUD operations.


Step 2: Create the Product Model

To work with data in a structured way, we need a model to represent the entity we’re working with. In this example, we’ll use a Product class that holds details like Product ID, Name, Description, and Price.

  1. In the Models folder (create it if it doesn’t exist), add a new class called Product.cs.
1namespace CrudApiDemo.Models
2{
3    public class Product
4    {
5        public int Id { get; set; }
6        public string Name { get; set; }
7        public string Description { get; set; }
8        public decimal Price { get; set; }
9    }
10}
11

This class will map to a Products table in your database.


Step 3: Set Up Entity Framework Core

Next, we need to set up Entity Framework Core to interact with our database. We’ll create a DbContext class to handle our database operations.

  1. In the Data folder, add a class called AppDbContext.cs.
1using Microsoft.EntityFrameworkCore;
2using CrudApiDemo.Models;
3
4namespace CrudApiDemo.Data
5{
6    public class AppDbContext : DbContext
7    {
8        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
9
10        public DbSet<Product> Products { get; set; }
11    }
12}
13

This class provides an abstraction over the database, allowing us to easily interact with our Product table.


Step 4: Configure Database Connection

Now, let’s configure the connection string in the appsettings.json file. This will allow our Web API to connect to a SQL Server database.

Open appsettings.json and add the following connection string:

1{
2  "ConnectionStrings": {
3    "DefaultConnection": "Server=localhost;Database=CrudApiDemoDb;Trusted_Connection=True;MultipleActiveResultSets=true"
4  },
5  ...
6}
7

Step 5: Register the DbContext

Now that we have our DbContext and connection string ready, we need to register it in the Startup.cs file.

  1. Open Startup.cs and locate the ConfigureServices method.
  2. Add the following code to register the DbContext:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

services.AddControllers();
}

This will allow our application to use the configured database when interacting with our Products data.


Step 6: Implementing the CRUD Operations

Next, we will create a controller to handle the CRUD operations. This controller will expose endpoints to Create, Read, Update, and Delete products.

  1. In the Controllers folder, add a new class called ProductsController.cs.
1using Microsoft.AspNetCore.Mvc;
2using Microsoft.EntityFrameworkCore;
3using CrudApiDemo.Data;
4using CrudApiDemo.Models;
5
6namespace CrudApiDemo.Controllers
7{
8    [Route("api/[controller]")]
9    [ApiController]
10    public class ProductsController : ControllerBase
11    {
12        private readonly AppDbContext _context;
13
14        public ProductsController(AppDbContext context)
15        {
16            _context = context;
17        }
18
19        // CREATE: api/products
20        [HttpPost]
21        public async Task<ActionResult<Product>> CreateProduct(Product product)
22        {
23            _context.Products.Add(product);
24            await _context.SaveChangesAsync();
25
26            return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
27        }
28
29        // READ: api/products
30        [HttpGet]
31        public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
32        {
33            return await _context.Products.ToListAsync();
34        }
35
36        // READ: api/products/{id}
37        [HttpGet("{id}")]
38        public async Task<ActionResult<Product>> GetProduct(int id)
39        {
40            var product = await _context.Products.FindAsync(id);
41
42            if (product == null)
43            {
44                return NotFound();
45            }
46
47            return product;
48        }
49
50        // UPDATE: api/products/{id}
51        [HttpPut("{id}")]
52        public async Task<IActionResult> UpdateProduct(int id, Product product)
53        {
54            if (id != product.Id)
55            {
56                return BadRequest();
57            }
58
59            _context.Entry(product).State = EntityState.Modified;
60            await _context.SaveChangesAsync();
61
62            return NoContent();
63        }
64
65        // DELETE: api/products/{id}
66        [HttpDelete("{id}")]
67        public async Task<IActionResult> DeleteProduct(int id)
68        {
69            var product = await _context.Products.FindAsync(id);
70            if (product == null)
71            {
72                return NotFound();
73            }
74
75            _context.Products.Remove(product);
76            await _context.SaveChangesAsync();
77
78            return NoContent();
79        }
80    }
81}
82

Step 7: Running Migrations and Updating the Database

Before we test the API, let’s apply migrations to create the Products table in the database.

  1. Open the Package Manager Console in Visual Studio.
  2. Run the following commands to create and apply the migrations:
Add-Migration InitialCreate
Update-Database

This will create the necessary database schema for our Product model.


Step 8: Testing the API

At this point, your Web API is set up to handle CRUD operations. You can now test the endpoints using Postman or directly via a browser.

Here are the available API routes:

  • Create a product: POST /api/products
  • Get all products: GET /api/products
  • Get a single product: GET /api/products/{id}
  • Update a product: PUT /api/products/{id}
  • Delete a product: DELETE /api/products/{id}

Conclusion

Congratulations! You’ve just implemented basic CRUD operations in a .NET Core Web API using Entity Framework Core. This foundation allows you to create robust and scalable REST APIs for managing data in your applications.

In this guide, we covered:

  • Setting up a Web API project.
  • Implementing CRUD operations.
  • Using Entity Framework Core to interact with a database.
  • Testing your Web API.

Feel free to extend this further by adding features like authentication, data validation, or pagination for larger datasets.

Let me know if you need further assistance or want to dive into more advanced features of .NET Core Web APIs!

Share this post:

Relevant Blog Posts

View All