How To Create Industry Standard .NET Core CRUD API Quickly

In this tutorial, we will learn how to create an N-tier Architecture in a .NET Core API with SOLID rules.

Overview

Practically speaking, designing CRUD-based applications is similar in all products. But still, we need to write the same code from scratch. Also, for CRUD applications, the most preferable pattern is the Repository pattern. However, it would be good if we have a generic tool that should be following the SOLID rules and is comfortable to use with all CRUD-related products. In this article, we are going to use the same repository pattern implemented with NuGet package RS2.Core.

So, in this article, we are going to -

  • create a business logic
  • create a Web API project
  • add a model class and database context.
  • register dependencies

Prerequisites

Creating Business Logic

Select the Add -> New Project menu option. On the "New Project" dialog, select .NET Core from the left side and select Class Library (.NET Core) template on the right side.

How To Create Industry Standard .NET Core CRUD API Quickly 

Give your project a name, select a folder where you want your project to be created, and click OK. This will create your first .NET Core Class Library project. I gave my project the name “BusinessLogic”.

Right-click the solution and select "Manage NuGet Packages for Solution".

How To Create Industry Standard .NET Core CRUD API Quickly 

Select the "Browse" tab and search for RS2.Core.

How To Create Industry Standard .NET Core CRUD API Quickly 

Mark the BusinessLogic project on the right side and click "Install". Press "I Accept" on the license appliance.

Add three different folders for Entities, Logics, and Context respectively under the BusinessLogic project.

Create Entities

Entities should be inherited from the Core Library which contains the required properties. For example - ID field (generic type), IsActive. EntityBase is the base class for master entities and EntityTranBase is for transaction entities, which contains the create and update properties. Let's create the Category and Product entities for now.

Category

  • Rename the "Class1" on Solution Explorer as "Category".
  • Move it to the "Entities" folder.
  • Replace with the below code.

  1. using System;  
  2. using RS2.Core;  
  3. namespace BusinessLogic {  
  4.     public class Category: EntityBase < int > {  
  5.         public string CategoryName {  
  6.             get;  
  7.             set;  
  8.         }  
  9.         public string ImageURL {  
  10.             get;  
  11.             set;  
  12.         }  
  13.     }  

Product

  • Right-click the "Entities" folder.
  • Select Add > Class.
  • Name the class Product, select "Add".
  • Replace with the below code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using RS2.Core;  
  4. namespace BusinessLogic {  
  5.     public class Product: EntityBase < long > {  
  6.         public string ProductName {  
  7.             get;  
  8.             set;  
  9.         }  
  10.         public decimal Price {  
  11.             get;  
  12.             set;  
  13.         }  
  14.         public int CategoryId {  
  15.             get;  
  16.             set;  
  17.         }  
  18.         public virtual Category Category {  
  19.             get;  
  20.             set;  
  21.         }  
  22.     }  
  23. }  

Create DB Context

For Code-First approach, we just create a context class and create DbSet objects for each entity. Let's create them for Product and Category Eitities.

  • Right-click the "Context" folder
  • Select Add > Class.
  • Name the class as ShoppingContext, select "Add".
  • Replace with the below code.

  1. using Microsoft.EntityFrameworkCore;  
  2. namespace BusinessLogic {  
  3.     public class ShoppingContext: DbContext {  
  4.         public ShoppingContext(DbContextOptions < ShoppingContext > options): base(options) {  
  5.             Database.EnsureCreated();  
  6.         }  
  7.         public DbSet < Category > Categories {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public DbSet < Product > Products {  
  12.             get;  
  13.             set;  
  14.         }  
  15.     }  
  16. }  

Create Business Logic classes

Creating business logic with the RS2.Core library is very simple. We need to create an interface for each entity and inherit the interface from IRepositoryBase for CRUD required entities or IGetRepository for read-only entities (Ex: Country, this object does not require an add or edit screen). Now, the Business class should be inherited from the interface created from RepositoryBase class from Core Library and the interface we have created for the entity. Let's create the same for the Product and Category entities.

Category Repository

  • Right-click the Logics folder.
  • Select Add > Class
  • Name the class CategoryRepository
  • Select "Add"
  • Replace with the below code.

  1. using RS2.Core;  
  2. namespace BusinessLogic {  
  3.     public interface ICategoryRepository: IRepositoryBase < Category, int > {}  
  4.     public class CategoryRepository: RepositoryBase < Category, int > , ICategoryRepository {  
  5.         public CategoryRepository(IUnitOfWork unitOfWork): base(unitOfWork) {}  
  6.     }  
  7. }  

Product Repository

  • Right-click the Logics folder.
  • Select Add > Class.
  • Name the class ProductRepository.
  • Select "Add".
  • Replace with the below code.

  1. using RS2.Core;  
  2. using Microsoft.EntityFrameworkCore;  
  3. namespace BusinessLogic {  
  4.     public interface IProductRepository: IRepositoryBase < Product, long > {}  
  5.     public class ProductRepository: RepositoryBase < Product, long > , IProductRepository {  
  6.         public ProductRepository(IUnitOfWork unitOfWork): base(unitOfWork) {}  
  7.         protected override IQueryable < Product > GetAllAsyncQuery(bool excludeDeleted = true) {  
  8.             return Entity.Include(e => e.Category).Where(p => !excludeDeleted || p.IsActive);  
  9.         }  
  10.     }  
  11. }  

Creating API

Now, let's create a Web API project and create the ASPI for both Category and Product eitities. Add a new project with the below steps.

  • Right-click the solution.
  • Select Add > New Project.
  • Select Web > ASP.NET Core Web Applications.
  • Name the project as API, select OK.
  • Now, select the API template and press OK.
  • Right-click solution.
  • Select "Manage NuGet Packages for Solution".
  • Choose the Installed tab and select RS2.Core.
  • Mark Api project at right side window and click install.
  • Accept the license for installation to complete.

    How To Create Industry Standard .NET Core CRUD API Quickly

Adding a Business Logic project reference to the API project

To use business entities and logic in the API project, we are adding the BusinessLogic project reference to the API project using the below steps.

  • Right-click on the dependencies of API project
  • Select "Add Reference".
  • Select the Projects tab on the left side.
  • Mark the BusinessLogic from the list and press OK.
Now, create the API controllers for Category and Product by the below-given steps.

Category Controller
  • Right-click the Controllers folder.
  • Select Add > Controller, select the API Controller - Empty template.
  • In the "Add New Item" dialog, name the class CategoriesController, select Add.

Let's call the CRUD operations from business logic. The below code will explain how to call business logic from our API for the Category entity.

  1. using System.Collections.Generic;  
  2. using System.Threading.Tasks;  
  3. using Microsoft.AspNetCore.Mvc;  
  4. using RS2.Core;  
  5. using BusinessLogic;  
  6. namespace Api.Controllers {  
  7.     [Produces("application/json")]  
  8.     [Route("api/[controller]")]  
  9.     [ApiController]  
  10.     public class CategoriesController: ControllerBase {  
  11.         private ICategoryRepository _categoryRepository;  
  12.         private IUnitOfWork _unitOfWork;  
  13.         public CategoriesController(ICategoryRepository categoryRepository, IUnitOfWork unitOfWork) {  
  14.             _categoryRepository = categoryRepository;  
  15.             _unitOfWork = unitOfWork;  
  16.         }  
  17.         // GET: api/Categories
  18.         [HttpGet]  
  19.         public async Task < IEnumerable < Category >> Get() {  
  20.             return await _categoryRepository.GetAllAsync();  
  21.         }  
  22.         // GET: api/Categories/5  
  23.         [HttpGet("{id}")]  
  24.         public async Task < Category > Get(int id) {  
  25.             return await _categoryRepository.GetAsync(id);  
  26.         }  
  27.         // POST: api/Categories 
  28.         [HttpPost]  
  29.         public async Task Post([FromBody] Category category) {  
  30.             await _categoryRepository.SaveAsync(category);  
  31.             // Commit the changes.  
  32.             await _unitOfWork.CommitAsync();  
  33.         }  
  34.         // DELETE: api/ApiWithActions/5  
  35.         [HttpDelete("{id}")]  
  36.         public async Task Delete(int id) {  
  37.             await _categoryRepository.SoftDelete(id); // Set Deleted flag.  
  38.             //await _categoryRepository.HardDelete(id); // Delete from DB  
  39.             // Commit the changes.  
  40.             await _unitOfWork.CommitAsync();  
  41.         }  
  42.     }  
  43. }  

Products Controller

  • Right-click the Controllers folder.
  • Select Add > Controller, select the API Controller - Empty template.
  • In the "Add New Item" dialog, name the class as ProductsController, select Add.
The below code will explain how to call the API methods from business logic for the Product entity.

  1. using System.Threading.Tasks;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using RS2.Core;  
  4. using BusinessLogic;  
  5. namespace Api.Controllers {  
  6.     [Produces("application/json")]  
  7.     [Route("api/[controller]")]  
  8.     [ApiController]  
  9.     public class ProductsController: ControllerBase {  
  10.         private IProductRepository _productRepository;  
  11.         private IUnitOfWork _unitOfWork;  
  12.         public ProductsController(IProductRepository productRepository, IUnitOfWork unitOfWork) {  
  13.             _productRepository = productRepository;  
  14.             _unitOfWork = unitOfWork;  
  15.         }  
  16.         // GET: api/Products  
  17.         [HttpGet]  
  18.         public async Task < IEnumerable < Proeuct >> Get() {  
  19.             return await _productRepository.GetAllAsync();  
  20.         }  
  21.         // GET: api/Products/5  
  22.         [HttpGet("{id}")]  
  23.         public async Task < Proeuct > Get(int id) {  
  24.             return await _productRepository.GetAsync(id);  
  25.         }  
  26.         // POST: api/Products  
  27.         [HttpPost]  
  28.         public async Task Post([FromBody] Product product) {  
  29.             await _productRepository.SaveAsync(product);  
  30.             // Commit the changes.  
  31.             await _unitOfWork.CommitAsync();  
  32.         }  
  33.         // DELETE: api/ApiWithActions/5  
  34.         [HttpDelete("{id}")]  
  35.         public async Task Delete(int id) {  
  36.             await _productRepository.SoftDelete(id); // Set Deleted flag.  
  37.             //await _productRepository.HardDelete(id); // Delete from DB  
  38.             // Commit the changes.  
  39.             await _unitOfWork.CommitAsync();  
  40.         }  
  41.     }  
  42. }  

Register the dependencies

Now, we need to register the dependencies, i.e., in the above controller code, we are just injecting the appropriate interface and calling the methods. So, we are configuring the dependency to that interface saying this interface contains the object for this class. For example, if we use IProductRepository, that should hold the object of ProductRepository class. These dependencies we are injecting at StartUp.cs. The below code will explain how to configure a dependency in StartUp.cs.

  1. public void ConfigureServices(IServiceCollection services)   
  2. {  
  3.     services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);  
  4.     services.AddDbContext < ShoppingContext > (options => options.UseSqlServer(Configuration.GetConnectionString("ShoppingConnection")));  
  5.     services.AddScoped < DbContext, ShoppingContext > ();  
  6.     services.AddScoped < IUnitOfWork, UnitOfWork > ();  
  7.     services.AddScoped < ICategoryRepository, CategoryRepository > ();  
  8.     services.AddScoped < IProductRepository, ProductRepository > ();  
  9. }  

We are done with the ApI creation. Below is the example of calling the API. Make sure you have configured the connection string properly in the appsettings.json file.

  • https://localhost:8080/api/products/2
  • https://localhost:8080/api/categories