Advertisement

Advertisement

CRUD Operation in Asp.Net Core Web API with Swagger

WEB API CORE CRUD USING SWAGGER

Steps :

Create Employee and Department Poco class.

Using Code First approach complete CRUD.

Test API using Swagger.

 

Step1)Add DI

microsoft.entityframeworkcore

microsoft.entityframeworkcore.design

microsoft.entityframeworkcore.sqlserver

microsoft.entityframeworkcore.tools

microsoft.extensions.configuration.json

microsoft.visualstudio.web.codegeneration.design

 

Step2)Make Models folder

Step3)Add poco class (Name=Employee)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

 

namespace WebApplicationWebApiSwagger.Models

{

    public class Employee

    {

        public int Id { get; set; }

        public string Name { get; set; }

        public string EmailId { get; set; }

      

        public Department Department { get; set; }

 

    }

}

 

Step4) Add poco class (Name=Department)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

 

namespace WebApplicationWebApiSwagger.Models

{

    public class Department

    {

        public int Id { get; set; }

        public string DepName { get; set; }

 

        public IList<Employee> Employees { get; set; }

    }

}

 

Step5)Add context class (Name=Employeecontext)

using Microsoft.EntityFrameworkCore;

 

namespace WebApplicationWebApiSwagger.Models

{

    public class Employeecontext : DbContext

    {

 

        public Employeecontext(DbContextOptions<Employeecontext> options)

             : base(options)

        {

        }

 

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

        public DbSet<Department> Departments { get; set; }

 

    }

}

 

Step6)Add connecting string in (appsettings.json)

{

  "Logging": {

    "LogLevel": {

      "Default": "Information",

      "Microsoft": "Warning",

      "Microsoft.Hosting.Lifetime": "Information"

    }

  },

  "ConnectionStrings": {

    "EmployeeDBConnection": "Data Source=(localdb)\\ProjectsV13;Initial Catalog=DBWebApiiii;Integrated Security=True;"

  },

  "AllowedHosts": "*"

}

Step6)Add Service in (Startup.cs)

  public void ConfigureServices(IServiceCollection services)

        {

 

            services.AddControllers();

            services.AddDbContext<Employeecontext>(

  options => options.UseSqlServer(Configuration.GetConnectionString("EmployeeDBConnection")));

            services.AddSwaggerGen(c =>

            {

                c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebApplicationWebApiSwagger", Version = "v1" });

            });

        }

 

Step7)Migration

Add-migration abc

Update-database

Step8)Add controller

using Microsoft.AspNetCore.Http;

using Microsoft.AspNetCore.Mvc;

using Microsoft.EntityFrameworkCore;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

using WebApplicationWebApiSwagger.Models;

 

namespace WebApplicationWebApiSwagger.Controllers

{

    [Route("api/[controller]")]

    [ApiController]

    public class EmployeesController : ControllerBase

    {

        private readonly Employeecontext _context;

 

        public EmployeesController(Employeecontext context)

        {

            _context = context;

        }

 

        // GET: api/Employees

        [HttpGet]

        public async Task<ActionResult<IEnumerable<Employee>>> GetEmployees()

        {

            return await _context.Employees.ToListAsync();

        }

 

        // GET: api/Employees/5

        [HttpGet("{id}")]

        public async Task<ActionResult<Employee>> GetEmployee(int id)

        {

            var employee = await _context.Employees.FindAsync(id);

 

            if (employee == null)

            {

                return NotFound();

            }

 

            return employee;

        }

 

        // PUT: api/Employees/5

        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754

        [HttpPut("{id}")]

        public async Task<IActionResult> PutEmployee(int id, Employee employee)

        {

            if (id != employee.Id)

            {

                return BadRequest();

            }

 

            _context.Entry(employee).State = EntityState.Modified;

 

            try

            {

                await _context.SaveChangesAsync();

            }

            catch (DbUpdateConcurrencyException)

            {

                if (!EmployeeExists(id))

                {

                    return NotFound();

                }

                else

                {

                    throw;

                }

            }

 

            return NoContent();

        }

 

        // POST: api/Employees

        // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754

        [HttpPost]

        public async Task<ActionResult<Employee>> PostEmployee(Employee employee)

        {

            _context.Employees.Add(employee);

            await _context.SaveChangesAsync();

 

            return CreatedAtAction("GetEmployee", new { id = employee.Id }, employee);

        }

 

        // DELETE: api/Employees/5

        [HttpDelete("{id}")]

        public async Task<IActionResult> DeleteEmployee(int id)

        {

            var employee = await _context.Employees.FindAsync(id);

            if (employee == null)

            {

                return NotFound();

            }

 

            _context.Employees.Remove(employee);

            await _context.SaveChangesAsync();

 

            return NoContent();

        }

 

        private bool EmployeeExists(int id)

        {

            return _context.Employees.Any(e => e.Id == id);

        }

    }

}

CRUD Operation in Asp.Net Core Web API with Swagger CRUD Operation in Asp.Net Core Web API with Swagger Reviewed by Rikesh on October 08, 2023 Rating: 5

No comments:

Powered by Blogger.