Skip to main content

CRUD operations in web api using net 6.0

.NET 6.0 - CRUD API Example and Tutorial

This tutorial gives you step by step implementation of creating CRUD operations using ASP.NET Web API Core.

This tutorial builds API for its clients to manage employee. it shows how to configure the SQL server connection to manage CRUD operations in real-time applications.

Let's start step by step.

1. Create ASP.NET Web API Project

Open your Visual Studio and select New Project from File Menu.

 

Now enter the name of the application and click next.

CRUD Operation Using NET CORE

 

Next select framework .net 6 from drop down and enable open API (Swagger) support and click on create to create default project template for API.
 

ASP.NET Core Web API

2. Now Add Model to Employee Web API

In this step, you will add the Employee Model Class which will define database entity.

Right click on the project from solution explorer and select Add -> New Folder. Enter folder name as Models.

Right click on the Models folder and select Add -> Class and add class file with name Employee.cs.

Now you can add Employee model properties as shown below.

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace EmployeeWebAPI.Models
{
    public class Employee
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int EmpId { get; set; }

        public string? FirstName { get; set; }

        public string? LastName { get; set; }

        public string? Email { get; set; }

        public string? PhoneNumber { get; set; }
    }
}

3. Create Database Context File

Database context file is main class file that is connect application to database.

Before add DB Context file you need to add microsoft.entityframeworkcore.sqlserver package using nuget package manager

Add a new class file with name EmpDBContext.cs to Models folder and add the below code.


using Microsoft.EntityFrameworkCore;

namespace EmployeeWebAPI.Models
{
    public class EmpDBContext : DbContext
    {
        public EmpDBContext(DbContextOptions<Empdbcontext> options)
        : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            modelBuilder.Entity<Employee>().ToTable("Employee");
        }


        public DbSet<Employee> Employee { get; set; }
    }
}

4. Add Web API Controller

Web API Controller is responsible for accepting the client's HTTP request, process request through Action methods and return the result.

Right click on Controllers folder, select Add -> Controller. You will see Add Scaffold dialog box, select API Controller - Empty name it as EmployeeController.cs and click Ok


using EmployeeWebAPI.Models;
using Microsoft.AspNetCore.Mvc;

namespace EmployeeWebAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        private readonly EmpDBContext _EmpDBContext;

        public EmployeeController(EmpDBContext EmpDBContext)
        {
            _EmpDBContext = EmpDBContext;
        }

        [HttpGet]
        public IActionResult Get()
        {
            return Ok(_EmpDBContext.Employee.ToList());
        }


        [HttpGet("{id}")]
        public IActionResult Get(int id)
        {
            return Ok(_EmpDBContext.Employee.FirstOrDefault(c => c.EmpId == id));
        }


        [HttpPost]
        public IActionResult Post([FromBody] Employee employee)
        {
            _EmpDBContext.Employee.Add(employee);
            _EmpDBContext.SaveChanges();

            return Ok("Employee created");
        }


        [HttpPut]
        public IActionResult Put([FromBody] Employee employee)
        {
            var emp = _EmpDBContext.Employee.FirstOrDefault(c => c.EmpId == employee.EmpId);

            if (emp == null)
                return BadRequest();

            emp.FirstName = employee.FirstName;
            emp.LastName = employee.LastName;
            emp.Email = employee.Email;
            emp.PhoneNumber = employee.PhoneNumber;

            _EmpDBContext.Employee.Update(emp);
            _EmpDBContext.SaveChanges();

            return Ok("Employee updated");
        }


        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            var emp = _EmpDBContext.Employee.FirstOrDefault(c => c.EmpId == id);

            if (emp == null)
                return BadRequest();

            _EmpDBContext.Employee.Remove(emp);
            _EmpDBContext.SaveChanges();

            return Ok("Employee deleted");
        }
    }
}

Implement GET Method using HttpGet

In this step, you will implement a GET Web API to read Employee details. Get methods can be used to get all employees depending on filters or get specific employee.

[HttpGet]
public IActionResult Get()
{
    return Ok(_EmpDBContext.Employee.ToList());
}


[HttpGet("{id}")]
public IActionResult Get(int id)
{
    return Ok(_EmpDBContext.Employee.FirstOrDefault(c => c.EmpId == id));
}

Implement Post Method using HttpPost

The HTTP POST method is used to create a new record in the data source in the RESTful architecture.

So Put action method in our EmployeeController to update an existing employee record in the database using Entity Framework.

[HttpPost]
public IActionResult Post([FromBody] Employee employee)
{
    _EmpDBContext.Employee.Add(employee);
    _EmpDBContext.SaveChanges();

    return Ok("Employee created");
}

This code accepts HTTPPost requests. [FromBody] attribute says use details of the new employee from the HTTP request body. It creates a new employee using DbContext to the database.

Implement Put method using HttpPut

The HTTP PUT method is used to update an existing record in the data source in the RESTful architecture.

So Put action method in our EmployeeController to update an existing employee record in the database using Entity Framework.

[HttpPut]
public IActionResult Put([FromBody] Employee employee)
{
	var emp = _EmpDBContext.Employee.FirstOrDefault(c => c.EmpId == employee.EmpId);

	if (emp == null)
		return BadRequest();
        
	emp.FirstName = employee.FirstName;
	emp.LastName = employee.LastName;
	emp.Email = employee.Email;
	emp.PhoneNumber = employee.PhoneNumber;

	_EmpDBContext.Employee.Update(emp);
	_EmpDBContext.SaveChanges();

	return Ok("Employee updated");
}

As you can see in the above figure, HTTP PUT request includes Employee object into JSON format in the request body. After successfull execution the request it'll return Employee updated response.

Implement Delete method using HttpDelete

The HTTP DELETE request is used to delete an existing record in the data source in the RESTful architecture.

So Delete action method in our EmployeeController to delete an existing employee record in the database using Entity Framework.

[HttpDelete("{id}")]
public IActionResult Delete(int id)
{
	var emp = _EmpDBContext.Employee.FirstOrDefault(c => c.EmpId == id);

	if (emp == null)
		return BadRequest();

	_EmpDBContext.Employee.Remove(emp);
	_EmpDBContext.SaveChanges();

	return Ok("Employee deleted");
}

As you can see above, Delete action method includes an id parameter of int type because it just needs an id to delete a record. It fetches an existing employee from the database that matches with the specified id and then marks its status as deleted. This will delete a employee from the database.

5. Add Connection String

Now in this step you need to add connection string in appsettings.json file to connect with database as shown below.


{
  "ConnectionStrings": {
    "DefaultConnection": "Server=yourservername;Database=Test;Trusted_Connection=Employee;User ID=yoursqlusername;Password=yoursqldatabasepassword;"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}

Now add EmpDBContext.cs class as service to the container in Program.cs file. So you can use that service in your controller as dependency injection. Here you can see how Program.cs look like after you added code.

using Microsoft.EntityFrameworkCore;
using EmployeeWebAPI.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddDbContext<EmpDBContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

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

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

6. Run Project

Now run your project and it'll look like as below.

swagger api example

 

Comments

Popular posts from this blog

Angular 14 CRUD Operation with Web API .Net 6.0

How to Perform CRUD Operation Using Angular 14 In this article, we will learn the angular crud (create, read, update, delete) tutorial with ASP.NET Core 6 web API. We will use the SQL Server database and responsive user interface for our Web app, we will use the Bootstrap 5. Let's start step by step. Step 1 - Create Database and Web API First we need to create Employee database in SQL Server and web API to communicate with database. so you can use my previous article CRUD operations in web API using net 6.0 to create web API step by step. As you can see, after creating all the required API and database, our API creation part is completed. Now we have to do the angular part like installing angular CLI, creating angular 14 project, command for building and running angular application...etc. Step 2 - Install Angular CLI Now we have to install angular CLI into our system. If you have already installed angular CLI into your system then skip this step.  To install angular CLI open vis

Angular 14 : 404 error during refresh page after deployment

In this article, We will learn how to solve 404 file or directory not found angular error in production.  Refresh browser angular 404 file or directory not found error You have built an Angular app and created a production build with ng build --prod You deploy it to a production server. Everything works fine until you refresh the page. The app throws The requested URL was not found on this server message (Status code 404 not found). It appears that angular routing not working on the production server when you refresh the page. The error appears on the following scenarios When you type the URL directly in the address bar. When you refresh the page The error appears on all the pages except the root page.   Reason for the requested URL was not found on this server error In a Multi-page web application, every time the application needs to display a page it has to send a request to the web server. You can do that by either typing the URL in the address bar, clicking on the Menu link/

React js CRUD Example Step by Step

How to build basic CRUD app with ReactJS Here's an example of building a simple CRUD application for managing a list of books. Step 1: Set up the React application To set up the React application, you'll need to have Node.js and NPM installed on your computer. Open a terminal or command prompt and create a new directory for your project. mkdir react-crud-app cd react-crud-app Next, initialize a new React application using the create-react-app CLI. npx create -react-app . Step 2: Create a list of books In this step, you'll create a list of books and display them in a table. Create a new file BookList.js in the src directory and add the following code: import React from 'react' ; const BookList = ( { books } ) => { return ( < table > < thead > < tr > < th > Title </ th > < th > Author </ th > < th > Actions </ th > </ tr > &