Create A Web API With Entity Framework Core In .NET 6

Create A Web API With Entity Framework Core In .NET 6

Divya Vaishanav

18 Jun 2024

8 MINUTES READ

Introduction

In this tutorial, we will create a simple web API for managing a list of products. We will use .NET 6, the latest version of Microsoft's .NET framework, and Entity Framework Core (EF Core) for database operations. By the end of this guide, you will have a fully functional API that can handle CRUD operations.

Prerequisites

Before we start, make sure you have the following installed:

Setting Up the Project

Create a New Project

Open your terminal or command prompt and run the following command to create a new ASP.NET Core Web API project:


    await Firebase.initializeApp(
        options: DefaultFirebaseOptions.currentPlatform,
    );              
    
Open the Project

If you are using Visual Studio, open the .csproj file. If you prefer Visual Studio Code, open the project directory.

Configuring entity framework Core

Install EF Core Packages

Run the following commands to install the necessary EF Core packages:


    dotnet add package Microsoft.EntityFrameworkCore
    dotnet add package Microsoft.EntityFrameworkCore.SqlServer
    dotnet add package Microsoft.EntityFrameworkCore.Tools                   
    
Add Connection String

Open the appsettings.json file and add your database connection string:


    {
        "ConnectionStrings": {
            "DefaultConnection":
            "Server=(localdb)\\mssqllocaldb;Database=ProductDb;Trusted_Connection=True;"
        },
        ...
    }                            
    

Creating the data model

Define the Product Model

Create a new folder named Models and add a Product.cs file with the following content:


    namespace ProductApi.Models
    {
        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public decimal Price { get; set; }
        }
    }                         
    

Setting up the database context

Create the Database Context

Add a new folder named Data and create a ProductContext.cs file with the following content:


        using Microsoft.EntityFrameworkCore;
        using ProductApi.Models;
        
        namespace ProductApi.Data
        {
            public class ProductContext : DbContext
            {
                public ProductContext(DbContextOptions options) : base(options)
                {
                }
        
                public DbSet Products { get; set; }
            }
        }                             
        
Register the Database Context

Open the Program.cs file and add the following code to register the ProductContext:


    using Microsoft.EntityFrameworkCore;
    using ProductApi.Data;

        var builder = WebApplication.CreateBuilder(args);

        // Add services to the container.
        builder.Services.AddControllers();
        builder.Services.AddDbContext(options =>
        options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

        var app = builder.Build();

        // Configure the HTTP request pipeline.
        if (app.Environment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

    app.UseHttpsRedirection();
    app.UseAuthorization();
    app.MapControllers();
    app.Run();            
        

Creating the API controllers

Create the Products Controller

Create a new folder named Controllers and add a ProductsController.cs file with the following content:


    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using ProductApi.Data;
    using ProductApi.Models;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    
    namespace ProductApi.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class ProductsController: ControllerBase
        {
            private readonly ProductContext _context;
    
            public ProductsController(ProductContext context)
            {
                _context = context;
            }
    
            // GET: api/Products
            [HttpGet]
            public async Task<ActionResult> GetProducts()
            {
                return await _context.Products.ToListAsync();
            }
    
            // GET: api/Products/5
            [HttpGet("{id}")]
            public async Task GetProduct(int id)
            {
                var product = await _context.Products.FindAsync(id);
    
                if (product == null)
                {
                    return NotFound();
                }
    
                return product;
            }
    
            // POST: api/Products
            [HttpPost]
            public async Task PostProduct(Product product)
            {
                _context.Products.Add(product);
                await _context.SaveChangesAsync();
    
                return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
            }
    
            // PUT: api/Products/5
            [HttpPut("{id}")]
            public async Task PutProduct(int id, Product product)
            {
                if (id != product.Id)
                {
                    return BadRequest();
                }
    
                _context.Entry(product).State = EntityState.Modified;
                await _context.SaveChangesAsync();
    
                return NoContent();
            }
    
            // DELETE: api/Products/5
            [HttpDelete("{id}")]
            public async Task DeleteProduct(int id)
            {
                var product = await _context.Products.FindAsync(id);
                if (product == null)
                {
                    return NotFound();
                }
    
                _context.Products.Remove(product);
                await _context.SaveChangesAsync();
    
                return NoContent();
            }
        }
    }                                
        

Testing the API

Run the Application

Use the following command to run your application:


    dotnet run
    
Run the Application

Use a tool like Postman or Swagger (which is integrated into the default template) to test the API endpoints.

  • GET api/products - Retrieve all products
  • GET api/products/{id} - Retrieve a product by ID
  • POST api/products - Create a new product
  • PUT api/products/{id} - Update an existing product
  • DELETE api/products/{id} - Delete a product

Conclusion

Congratulations! You've successfully created a Web API with Entity Framework Core in .NET 6. This guide has covered the basics of setting up a project, configuring EF Core, creating data models, setting up the database context, and building API controllers. With this foundation, you can expand your API to include more features and complexity as needed.

FAQ

To create a Web API with Entity Framework Core in .NET 6, you need .NET 6 SDK, Visual Studio 2022 or Visual Studio Code, and SQL Server (or SQL Server Express).

Open your terminal or command prompt and run dotnet new webapi -n ProductApi followed by cd ProductApi to create and navigate to the new project directory.

The Product model is defined in the ProductApi.Models namespace with properties for Id, Name, and Price.

Create a ProductsController class in a Controller folder, inheriting from ControllerBase. Implement CRUD operations using HTTP methods like GET, POST, PUT, and DELETE.

Run your application using dotnet run and test the endpoints with tools like Postman or Swagger. Use the endpoints to perform CRUD operations on products.

Divya Vaishanav
Divya Vaishanav

Marketing Executive

Divya Vaishnav is a dynamic Marketing Executive known for her innovative strategies and keen market insights. With a talent for crafting compelling campaigns, she drives brand growth and customer engagement.

Linkedin
Hire Skilled Developer

*Please fill all the required fields

Get our Newsletter

Customized solutions for your projects

*Please fill all the required fields