CRUD Operation In ASP.NET Core 5 Web API

Introduction

 
In this article, I will discuss the complete procedure of crud operation in Asp.Net Core 5 Web API project. We will send the complete JSON object to the POST endpoint and then we will update the data in the database using PUT Endpoint. Basically, in this project we will perform the complete CRUD operation using Asp.Net 5 Architecture. We will perform the following operation like POST PUT DELETE GET operations. POST Method is used for sending the JSON Data to database PUT Method is used to update the Data in Database DELETE Method is used to delete the data from the database either based on Id OR Compete Data from Database GET Method is used for Getting all the record from the database either on the bases of Id or All Data in the form of JSON objects. I will apply the repository pattern in this project CRUDAspNetCore5Web API
Resources can be downloaded from Article Resource Section.
 

Project Setup

 
Add Asp.Net Core 5 Project
 
Start the Asp.Net Core project using the Visual Studio in Asp.net Core with the latest version .Net Core Version 5.
 
CRUD Operation
 
CRUD Operation
 
Add DAL_CRUD Asp.net Core Class Library
 
Add the .Net class Library for DAL (Data Access Layer) in Data Access Layer we will connect our ORM With Database and we will define some methods for doing our all logic in the business access layer.
 
 
CRUD Operation
 
Add BAL_CRUD Asp.net Core Class Library
 
Add the .Net class Library for DAL (Business Access Layer). In the Business Access layer, we will use the basic structure of our ORM that is already defined in the data access layer. In our business access layer, we will perform our all logic about our Crud Operations like POST GET PUT AND Delete.
 
CRUD Operation
 
CRUD Operation
 
Data Access Layer
 
In the Data Access layer we will perform the following steps,
 
Application Db Context
 
First, add the connection string in the application Setting.JSON file and then connect the connection string with Application Db Class then call the string connection in Startup. cs class for establishing the connection with the database.
 
CRUD Operation
  1. using CRUD_DAL.Models;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Text;  
  6.   
  7. namespace CRUD_DAL.Data  
  8. {  
  9.     public class ApplicationDbContext : DbContext  
  10.     {  
  11.   
  12.         public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)  
  13.         {  
  14.   
  15.         }  
  16.         protected override void OnModelCreating(ModelBuilder builder)  
  17.         {  
  18.             base.OnModelCreating(builder);  
  19.         }  
  20.         public DbSet<Person> Persons { get; set; }  
  21.     }  
  22. }   
Application Setting.JSON file
  1. {  
  2.   "Logging": {  
  3.     "LogLevel": {  
  4.       "Default""Information",  
  5.       "Microsoft""Warning",  
  6.       "Microsoft.Hosting.Lifetime""Information"  
  7.     }  
  8.   },  
  9.   "AllowedHosts""*",  
  10.   "ConnectionStrings": {  
  11.     // "DefaultConnection": "Server=SARDARMUDASSARA\\SQLEXPRESS;Initial Catalog=CRUDWEAPI;Persist Security Info=False;User ID=MudassarAliKhan;Password=12345;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;"  
  12.     "DefaultConnection""Server=SARDARMUDASSARA\\SQLEXPRESS;Database=CRUDAspNetCore5WebAPI;Trusted_Connection=True"  
  13.   }  
  14. }  
Start-Up File
  1. using CRUD_BAL.Service;  
  2. using CRUD_DAL.Data;  
  3. using CRUD_DAL.Interface;  
  4. using CRUD_DAL.Models;  
  5. using CRUD_DAL.Repository;  
  6. using Microsoft.AspNetCore.Builder;  
  7. using Microsoft.AspNetCore.Hosting;  
  8. using Microsoft.AspNetCore.HttpsPolicy;  
  9. using Microsoft.AspNetCore.Mvc;  
  10. using Microsoft.EntityFrameworkCore;  
  11. using Microsoft.Extensions.Configuration;  
  12. using Microsoft.Extensions.DependencyInjection;  
  13. using Microsoft.Extensions.Hosting;  
  14. using Microsoft.Extensions.Logging;  
  15. using Microsoft.OpenApi.Models;  
  16. using System;  
  17. using System.Collections.Generic;  
  18. using System.Linq;  
  19. using System.Threading.Tasks;  
  20.   
  21. namespace CRUDAspNetCore5WebAPI  
  22. {  
  23.     public class Startup  
  24.     {  
  25.         private readonly IConfiguration _configuration;  
  26.   
  27.         public Startup(IConfiguration configuration)  
  28.         {  
  29.             _configuration = configuration;  
  30.         }  
  31.   
  32.   
  33.         // This method gets called by the runtime. Use this method to add services to the container.  
  34.         public void ConfigureServices(IServiceCollection services)  
  35.         {  
  36.             services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));  
  37.             services.AddControllers();  
  38.             services.AddHttpClient();  
  39.             services.AddTransient<IRepository<Person>, RepositoryPerson>();  
  40.             services.AddTransient<PersonService, PersonService>();  
  41.             services.AddControllers();  
  42.             services.AddSwaggerGen(c =>  
  43.             {  
  44.                 c.SwaggerDoc("v1"new OpenApiInfo { Title = "CRUDAspNetCore5WebAPI", Version = "v1" });  
  45.             });  
  46.         }  
  47.   
  48.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  49.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  50.         {  
  51.             if (env.IsDevelopment())  
  52.             {  
  53.                 app.UseDeveloperExceptionPage();  
  54.                 app.UseSwagger();  
  55.                 app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json""CRUDAspNetCore5WebAPI v1"));  
  56.             }  
  57.   
  58.             app.UseHttpsRedirection();  
  59.   
  60.             app.UseRouting();  
  61.   
  62.             app.UseAuthorization();  
  63.   
  64.             app.UseEndpoints(endpoints =>  
  65.             {  
  66.                 endpoints.MapControllers();  
  67.             });  
  68.         }  
  69.     }  
  70. }  
Application Db Context Class
  1. using CRUD_DAL.Models;  
  2. using Microsoft.EntityFrameworkCore;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Text;  
  6.   
  7. namespace CRUD_DAL.Data  
  8. {  
  9.     public class ApplicationDbContext : DbContext  
  10.     {  
  11.   
  12.         public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)  
  13.         {  
  14.   
  15.         }  
  16.         protected override void OnModelCreating(ModelBuilder builder)  
  17.         {  
  18.             base.OnModelCreating(builder);  
  19.         }  
  20.         public DbSet<Person> Persons { getset; }  
  21.     }  
  22. }  
Model
 
Add the model class in which define the entity for the database and his attributes like Id Name, and Person Phone No.
 
CRUD Operation
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.ComponentModel.DataAnnotations.Schema;  
  5. using System.Text;  
  6.   
  7. namespace CRUD_DAL.Models  
  8. {  
  9.     [Table("Persons", Schema = "dbo")]  
  10.     public class Person  
  11.     {  
  12.         [Key]  
  13.         [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  14.         public int Id { getset; }  
  15.   
  16.         [Required]  
  17.         [Display(Name = "UserName")]  
  18.         public string UserName { getset; }  
  19.   
  20.         [Required]  
  21.         [Display(Name = "UserPassword")]  
  22.         public string UserPassword { getset; }  
  23.         [Required]  
  24.         [Display(Name = "UserEmail")]  
  25.         public string UserEmail { getset; }  
  26.   
  27.         [Required]  
  28.         [Display(Name = "CreatedOn")]  
  29.         public DateTime CreatedOn { getset; } = DateTime.Now;  
  30.   
  31.         [Required]  
  32.         [Display(Name = "IsDeleted")]  
  33.         public bool IsDeleted { getset; } = false;  
  34.   
  35.     }  
  36. }  
Migration
 
Now Add the migration for the creation of the database and after adding migration Update the database. Select the DAL project for the migration of Data
 
CRUD Operation
 
CRUD Operation  
CRUD Operation
 
Interface
 
Add the interface folder and then add the Interface in the data access layer In Interface and Define the Methods that you want to perform in the repository pattern.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Threading.Tasks;  
  5.   
  6. namespace CRUD_DAL.Interface  
  7. {  
  8.     public interface IRepository<T>  
  9.     {  
  10.         public Task<T> Create(T _object);  
  11.   
  12.         public void Update(T _object);  
  13.   
  14.         public IEnumerable<T> GetAll();  
  15.   
  16.         public T GetById(int Id);  
  17.   
  18.         public void Delete(T _object);  
  19.   
  20.     }  
  21. }  
Repository
 
Add the Repository Person Class Which Implements the Interface and performs the function defined in the interface like getting All Data, Delete All Data Update Data, Update data by userId like this.
 
CRUD Operation
  1. using CRUD_DAL.Data;  
  2. using CRUD_DAL.Interface;  
  3. using CRUD_DAL.Models;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Linq;  
  7. using System.Text;  
  8. using System.Threading.Tasks;  
  9.   
  10. namespace CRUD_DAL.Repository  
  11. {  
  12.     public class RepositoryPerson : IRepository<Person>  
  13.     {  
  14.         ApplicationDbContext _dbContext;  
  15.         public RepositoryPerson(ApplicationDbContext applicationDbContext)  
  16.         {  
  17.             _dbContext = applicationDbContext;  
  18.         }  
  19.         public async Task<Person> Create(Person _object)  
  20.         {  
  21.             var obj = await _dbContext.Persons.AddAsync(_object);  
  22.             _dbContext.SaveChanges();  
  23.             return obj.Entity;  
  24.         }  
  25.   
  26.         public void Delete(Person _object)  
  27.         {  
  28.             _dbContext.Remove(_object);  
  29.             _dbContext.SaveChanges();  
  30.         }  
  31.   
  32.         public IEnumerable<Person> GetAll()  
  33.         {  
  34.             try  
  35.             {  
  36.                 return _dbContext.Persons.Where(x => x.IsDeleted == false).ToList();  
  37.             }  
  38.             catch (Exception ee)  
  39.             {  
  40.                 throw;  
  41.             }  
  42.         }  
  43.   
  44.         public Person GetById(int Id)  
  45.         {  
  46.             return _dbContext.Persons.Where(x => x.IsDeleted == false && x.Id == Id).FirstOrDefault();  
  47.         }  
  48.   
  49.         public void Update(Person _object)  
  50.         {  
  51.             _dbContext.Persons.Update(_object);  
  52.             _dbContext.SaveChanges();  
  53.         }  
  54.     }  
  55. }  
Business Access Layer
 
Add Project Reference of Data Access Layer
 
Before Staring the Work on Person Service Class First Add the Reference of Data Access class library project in the Business access layer.
 
CRUD Operation
 
CRUD Operation
 
Person Service
 
In-Person Service We will use the Data Access Class Library in which we have already defined the Methods like Update Data Delete Data etc. But in business access, we will write all the business logic like getting all the data with a specific Id, update the complete object using userId, Soft Deletion of data.
 
Add the service folder in the business access layer then add the person service class.
 
CRUD Operation
  1. using CRUD_DAL.Interface;  
  2. using CRUD_DAL.Models;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Text;  
  7. using System.Threading.Tasks;  
  8.   
  9. namespace CRUD_BAL.Service  
  10. {  
  11.     public class PersonService  
  12.     {  
  13.         private readonly IRepository<Person> _person;  
  14.   
  15.         public PersonService(IRepository<Person> perosn)  
  16.         {  
  17.             _person = perosn;  
  18.         }  
  19.         //Get Person Details By Person Id  
  20.         public IEnumerable<Person> GetPersonByUserId(string UserId)  
  21.         {  
  22.             return _person.GetAll().Where(x => x.UserEmail == UserId).ToList();  
  23.         }  
  24.         //GET All Perso Details   
  25.         public IEnumerable<Person> GetAllPersons()  
  26.         {  
  27.             try  
  28.             {  
  29.                 return _person.GetAll().ToList();  
  30.             }  
  31.             catch (Exception)  
  32.             {  
  33.                 throw;  
  34.             }  
  35.         }  
  36.         //Get Person by Person Name  
  37.         public Person GetPersonByUserName(string UserName)  
  38.         {  
  39.             return _person.GetAll().Where(x => x.UserEmail == UserName).FirstOrDefault();  
  40.         }  
  41.         //Add Person  
  42.         public async Task<Person> AddPerson(Person Person)  
  43.         {  
  44.             return await _person.Create(Person);  
  45.         }  
  46.         //Delete Person   
  47.         public bool DeletePerson(string UserEmail)  
  48.         {  
  49.   
  50.             try  
  51.             {  
  52.                 var DataList = _person.GetAll().Where(x => x.UserEmail == UserEmail).ToList();  
  53.                 foreach (var item in DataList)  
  54.                 {  
  55.                     _person.Delete(item);  
  56.                 }  
  57.                 return true;  
  58.             }  
  59.             catch (Exception)  
  60.             {  
  61.                 return true;  
  62.             }  
  63.   
  64.         }  
  65.         //Update Person Details  
  66.         public bool UpdatePerson(Person person)  
  67.         {  
  68.             try  
  69.             {  
  70.                 var DataList = _person.GetAll().Where(x => x.IsDeleted != true).ToList();  
  71.                 foreach (var item in DataList)  
  72.                 {  
  73.                     _person.Update(item);  
  74.                 }  
  75.                 return true;  
  76.             }  
  77.             catch (Exception)  
  78.             {  
  79.                 return true;  
  80.             }  
  81.         }  
  82.     }  
  83. }   

API in Asp.Net Core 5 Web API

 
Add Project Reference of Business Access Layer
 
Before Staring in API Controllers first add the business access layer BAL Class library project reference in API Project.
 
CRUD Operation
 
CRUD Operation
 
Add the Transient in Startup Class
 
Modify the startup class like add the transient in the Startup class for adding the dependency injection transient services created whenever they are injected or requested.
  1. using CRUD_BAL.Service;  
  2. using CRUD_DAL.Data;  
  3. using CRUD_DAL.Interface;  
  4. using CRUD_DAL.Models;  
  5. using CRUD_DAL.Repository;  
  6. using Microsoft.AspNetCore.Builder;  
  7. using Microsoft.AspNetCore.Hosting;  
  8. using Microsoft.AspNetCore.HttpsPolicy;  
  9. using Microsoft.AspNetCore.Mvc;  
  10. using Microsoft.EntityFrameworkCore;  
  11. using Microsoft.Extensions.Configuration;  
  12. using Microsoft.Extensions.DependencyInjection;  
  13. using Microsoft.Extensions.Hosting;  
  14. using Microsoft.Extensions.Logging;  
  15. using Microsoft.OpenApi.Models;  
  16. using System;  
  17. using System.Collections.Generic;  
  18. using System.Linq;  
  19. using System.Threading.Tasks;  
  20.   
  21. namespace CRUDAspNetCore5WebAPI  
  22. {  
  23.     public class Startup  
  24.     {  
  25.         private readonly IConfiguration _configuration;  
  26.   
  27.         public Startup(IConfiguration configuration)  
  28.         {  
  29.             _configuration = configuration;  
  30.         }  
  31.   
  32.   
  33.         // This method gets called by the runtime. Use this method to add services to the container.  
  34.         public void ConfigureServices(IServiceCollection services)  
  35.         {  
  36.             services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));  
  37.             services.AddControllers();  
  38.             services.AddHttpClient();  
  39.             services.AddTransient<IRepository<Person>, RepositoryPerson>();  
  40.             services.AddTransient<PersonService, PersonService>();  
  41.             services.AddControllers();  
  42.             services.AddSwaggerGen(c =>  
  43.             {  
  44.                 c.SwaggerDoc("v1"new OpenApiInfo { Title = "CRUDAspNetCore5WebAPI", Version = "v1" });  
  45.             });  
  46.         }  
  47.   
  48.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  49.         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)  
  50.         {  
  51.             if (env.IsDevelopment())  
  52.             {  
  53.                 app.UseDeveloperExceptionPage();  
  54.                 app.UseSwagger();  
  55.                 app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json""CRUDAspNetCore5WebAPI v1"));  
  56.             }  
  57.   
  58.             app.UseHttpsRedirection();  
  59.   
  60.             app.UseRouting();  
  61.   
  62.             app.UseAuthorization();  
  63.   
  64.             app.UseEndpoints(endpoints =>  
  65.             {  
  66.                 endpoints.MapControllers();  
  67.             });  
  68.         }  
  69.     }  
  70. }   
API Controller
 
In API Controller We will Define Our GET PUT POST AND DELETE Endpoints for achieving our CRUD operation Goals.
 
CRUD Operation
 
CRUD Operation
 
CRUD Operation
 
CRUD Operation
 
CRUD Operation
  1. using CRUD_BAL.Service;  
  2. using CRUD_DAL.Interface;  
  3. using CRUD_DAL.Models;  
  4. using Microsoft.AspNetCore.Http;  
  5. using Microsoft.AspNetCore.Mvc;  
  6. using Newtonsoft.Json;  
  7. using System;  
  8. using System.Collections.Generic;  
  9. using System.Linq;  
  10. using System.Threading.Tasks;  
  11.   
  12. namespace CRUDAspNetCore5WebAPI.Controllers  
  13. {  
  14.     [Route("api/[controller]")]  
  15.     [ApiController]  
  16.     public class PersonDetailsController : ControllerBase  
  17.     {  
  18.         private readonly PersonService _personService;  
  19.   
  20.         private readonly IRepository<Person> _Person;  
  21.   
  22.         public PersonDetailsController(IRepository<Person> Person, PersonService ProductService)  
  23.         {  
  24.             _personService = ProductService;  
  25.             _Person = Person;  
  26.   
  27.         }  
  28.         //Add Person  
  29.         [HttpPost("AddPerson")]  
  30.         public async Task<Object> AddPerson([FromBody] Person person)  
  31.         {  
  32.             try  
  33.             {  
  34.                 await _personService.AddPerson(person);  
  35.                 return true;  
  36.             }  
  37.             catch (Exception)  
  38.             {  
  39.   
  40.                 return false;  
  41.             }  
  42.         }  
  43.         //Delete Person  
  44.         [HttpDelete("DeletePerson")]  
  45.         public bool DeletePerson(string UserEmail)  
  46.         {  
  47.             try  
  48.             {  
  49.                 _personService.DeletePerson(UserEmail);  
  50.                 return true;  
  51.             }  
  52.             catch (Exception)  
  53.             {  
  54.                 return false;  
  55.             }  
  56.         }  
  57.         //Delete Person  
  58.         [HttpPut("UpdatePerson")]  
  59.         public bool UpdatePerson(Person Object)  
  60.         {  
  61.             try  
  62.             {  
  63.                 _personService.UpdatePerson(Object);  
  64.                 return true;  
  65.             }  
  66.             catch (Exception)  
  67.             {  
  68.                 return false;  
  69.             }  
  70.         }  
  71.         //GET All Person by Name  
  72.         [HttpGet("GetAllPersonByName")]  
  73.         public Object GetAllPersonByName(string UserEmail)  
  74.         {  
  75.             var data = _personService.GetPersonByUserName(UserEmail);  
  76.             var json = JsonConvert.SerializeObject(data, Formatting.Indented,  
  77.                 new JsonSerializerSettings()  
  78.                 {  
  79.                     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore  
  80.                 }  
  81.             );  
  82.             return json;  
  83.         }  
  84.   
  85.         //GET All Person  
  86.         [HttpGet("GetAllPersons")]  
  87.         public Object GetAllPersons()  
  88.         {  
  89.             var data = _personService.GetAllPersons();  
  90.             var json = JsonConvert.SerializeObject(data, Formatting.Indented,  
  91.                 new JsonSerializerSettings()  
  92.                 {  
  93.                     ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore  
  94.                 }  
  95.             );  
  96.             return json;  
  97.         }  
  98.     }  
  99. }  
TESTING THE API
 
for Testing of API, I will Discuss the complete procedure in a separate article 
 
Project Resource Guideline
  • First, download the given Project from my GitHub repository / from article resources.
  • Open the project using visual studio
  • Go to package manager console
  • Add the migration
  • Update the database
  • Run the project
  • Enjoy the beauty of web service API with swagger UI
“Happy API Development”
 

Conclusion

 
As a software engineer, my opinion about RESTful web services is that it is a lightweight, maintainable, and scalable service that is built on the REST architecture. RESTful architecture provides us the best way to develop cross platforms applications using the Asp.net Core Web API. I suggest all the online communities that develop your Web application using RESTfull Web architecture and follow the best practices of coding for high efficiency of the application.