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.
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.
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.
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.
- using CRUD_DAL.Models;
- using Microsoft.EntityFrameworkCore;
- using System;
- using System.Collections.Generic;
- using System.Text;
-
- namespace CRUD_DAL.Data
- {
- public class ApplicationDbContext : DbContext
- {
-
- public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
- {
-
- }
- protected override void OnModelCreating(ModelBuilder builder)
- {
- base.OnModelCreating(builder);
- }
- public DbSet<Person> Persons { get; set; }
- }
- }
Application Setting.JSON file
- {
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft": "Warning",
- "Microsoft.Hosting.Lifetime": "Information"
- }
- },
- "AllowedHosts": "*",
- "ConnectionStrings": {
-
- "DefaultConnection": "Server=SARDARMUDASSARA\\SQLEXPRESS;Database=CRUDAspNetCore5WebAPI;Trusted_Connection=True"
- }
- }
Start-Up File
- using CRUD_BAL.Service;
- using CRUD_DAL.Data;
- using CRUD_DAL.Interface;
- using CRUD_DAL.Models;
- using CRUD_DAL.Repository;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.HttpsPolicy;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using Microsoft.OpenApi.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace CRUDAspNetCore5WebAPI
- {
- public class Startup
- {
- private readonly IConfiguration _configuration;
-
- public Startup(IConfiguration configuration)
- {
- _configuration = configuration;
- }
-
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
- services.AddControllers();
- services.AddHttpClient();
- services.AddTransient<IRepository<Person>, RepositoryPerson>();
- services.AddTransient<PersonService, PersonService>();
- services.AddControllers();
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new OpenApiInfo { Title = "CRUDAspNetCore5WebAPI", Version = "v1" });
- });
- }
-
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- app.UseSwagger();
- app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CRUDAspNetCore5WebAPI v1"));
- }
-
- app.UseHttpsRedirection();
-
- app.UseRouting();
-
- app.UseAuthorization();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
- }
Application Db Context Class
- using CRUD_DAL.Models;
- using Microsoft.EntityFrameworkCore;
- using System;
- using System.Collections.Generic;
- using System.Text;
-
- namespace CRUD_DAL.Data
- {
- public class ApplicationDbContext : DbContext
- {
-
- public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
- {
-
- }
- protected override void OnModelCreating(ModelBuilder builder)
- {
- base.OnModelCreating(builder);
- }
- public DbSet<Person> Persons { get; set; }
- }
- }
Model
Add the model class in which define the entity for the database and his attributes like Id Name, and Person Phone No.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.ComponentModel.DataAnnotations.Schema;
- using System.Text;
-
- namespace CRUD_DAL.Models
- {
- [Table("Persons", Schema = "dbo")]
- public class Person
- {
- [Key]
- [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
- public int Id { get; set; }
-
- [Required]
- [Display(Name = "UserName")]
- public string UserName { get; set; }
-
- [Required]
- [Display(Name = "UserPassword")]
- public string UserPassword { get; set; }
- [Required]
- [Display(Name = "UserEmail")]
- public string UserEmail { get; set; }
-
- [Required]
- [Display(Name = "CreatedOn")]
- public DateTime CreatedOn { get; set; } = DateTime.Now;
-
- [Required]
- [Display(Name = "IsDeleted")]
- public bool IsDeleted { get; set; } = false;
-
- }
- }
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
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.
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace CRUD_DAL.Interface
- {
- public interface IRepository<T>
- {
- public Task<T> Create(T _object);
-
- public void Update(T _object);
-
- public IEnumerable<T> GetAll();
-
- public T GetById(int Id);
-
- public void Delete(T _object);
-
- }
- }
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.
- using CRUD_DAL.Data;
- using CRUD_DAL.Interface;
- using CRUD_DAL.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace CRUD_DAL.Repository
- {
- public class RepositoryPerson : IRepository<Person>
- {
- ApplicationDbContext _dbContext;
- public RepositoryPerson(ApplicationDbContext applicationDbContext)
- {
- _dbContext = applicationDbContext;
- }
- public async Task<Person> Create(Person _object)
- {
- var obj = await _dbContext.Persons.AddAsync(_object);
- _dbContext.SaveChanges();
- return obj.Entity;
- }
-
- public void Delete(Person _object)
- {
- _dbContext.Remove(_object);
- _dbContext.SaveChanges();
- }
-
- public IEnumerable<Person> GetAll()
- {
- try
- {
- return _dbContext.Persons.Where(x => x.IsDeleted == false).ToList();
- }
- catch (Exception ee)
- {
- throw;
- }
- }
-
- public Person GetById(int Id)
- {
- return _dbContext.Persons.Where(x => x.IsDeleted == false && x.Id == Id).FirstOrDefault();
- }
-
- public void Update(Person _object)
- {
- _dbContext.Persons.Update(_object);
- _dbContext.SaveChanges();
- }
- }
- }
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.
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.
- using CRUD_DAL.Interface;
- using CRUD_DAL.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace CRUD_BAL.Service
- {
- public class PersonService
- {
- private readonly IRepository<Person> _person;
-
- public PersonService(IRepository<Person> perosn)
- {
- _person = perosn;
- }
-
- public IEnumerable<Person> GetPersonByUserId(string UserId)
- {
- return _person.GetAll().Where(x => x.UserEmail == UserId).ToList();
- }
-
- public IEnumerable<Person> GetAllPersons()
- {
- try
- {
- return _person.GetAll().ToList();
- }
- catch (Exception)
- {
- throw;
- }
- }
-
- public Person GetPersonByUserName(string UserName)
- {
- return _person.GetAll().Where(x => x.UserEmail == UserName).FirstOrDefault();
- }
-
- public async Task<Person> AddPerson(Person Person)
- {
- return await _person.Create(Person);
- }
-
- public bool DeletePerson(string UserEmail)
- {
-
- try
- {
- var DataList = _person.GetAll().Where(x => x.UserEmail == UserEmail).ToList();
- foreach (var item in DataList)
- {
- _person.Delete(item);
- }
- return true;
- }
- catch (Exception)
- {
- return true;
- }
-
- }
-
- public bool UpdatePerson(Person person)
- {
- try
- {
- var DataList = _person.GetAll().Where(x => x.IsDeleted != true).ToList();
- foreach (var item in DataList)
- {
- _person.Update(item);
- }
- return true;
- }
- catch (Exception)
- {
- return true;
- }
- }
- }
- }
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.
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.
- using CRUD_BAL.Service;
- using CRUD_DAL.Data;
- using CRUD_DAL.Interface;
- using CRUD_DAL.Models;
- using CRUD_DAL.Repository;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.HttpsPolicy;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using Microsoft.OpenApi.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace CRUDAspNetCore5WebAPI
- {
- public class Startup
- {
- private readonly IConfiguration _configuration;
-
- public Startup(IConfiguration configuration)
- {
- _configuration = configuration;
- }
-
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));
- services.AddControllers();
- services.AddHttpClient();
- services.AddTransient<IRepository<Person>, RepositoryPerson>();
- services.AddTransient<PersonService, PersonService>();
- services.AddControllers();
- services.AddSwaggerGen(c =>
- {
- c.SwaggerDoc("v1", new OpenApiInfo { Title = "CRUDAspNetCore5WebAPI", Version = "v1" });
- });
- }
-
-
- public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- app.UseSwagger();
- app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CRUDAspNetCore5WebAPI v1"));
- }
-
- app.UseHttpsRedirection();
-
- app.UseRouting();
-
- app.UseAuthorization();
-
- app.UseEndpoints(endpoints =>
- {
- endpoints.MapControllers();
- });
- }
- }
- }
API Controller
In API Controller We will Define Our GET PUT POST AND DELETE Endpoints for achieving our CRUD operation Goals.
- using CRUD_BAL.Service;
- using CRUD_DAL.Interface;
- using CRUD_DAL.Models;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Newtonsoft.Json;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
-
- namespace CRUDAspNetCore5WebAPI.Controllers
- {
- [Route("api/[controller]")]
- [ApiController]
- public class PersonDetailsController : ControllerBase
- {
- private readonly PersonService _personService;
-
- private readonly IRepository<Person> _Person;
-
- public PersonDetailsController(IRepository<Person> Person, PersonService ProductService)
- {
- _personService = ProductService;
- _Person = Person;
-
- }
-
- [HttpPost("AddPerson")]
- public async Task<Object> AddPerson([FromBody] Person person)
- {
- try
- {
- await _personService.AddPerson(person);
- return true;
- }
- catch (Exception)
- {
-
- return false;
- }
- }
-
- [HttpDelete("DeletePerson")]
- public bool DeletePerson(string UserEmail)
- {
- try
- {
- _personService.DeletePerson(UserEmail);
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
-
- [HttpPut("UpdatePerson")]
- public bool UpdatePerson(Person Object)
- {
- try
- {
- _personService.UpdatePerson(Object);
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
-
- [HttpGet("GetAllPersonByName")]
- public Object GetAllPersonByName(string UserEmail)
- {
- var data = _personService.GetPersonByUserName(UserEmail);
- var json = JsonConvert.SerializeObject(data, Formatting.Indented,
- new JsonSerializerSettings()
- {
- ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
- }
- );
- return json;
- }
-
-
- [HttpGet("GetAllPersons")]
- public Object GetAllPersons()
- {
- var data = _personService.GetAllPersons();
- var json = JsonConvert.SerializeObject(data, Formatting.Indented,
- new JsonSerializerSettings()
- {
- ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
- }
- );
- return json;
- }
- }
- }
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.