Implementing Generic Repository And CRUD Operations In ASP.NET Core Web API

Creating a new project

Create a new project in Visual Studio 2017/2019. 
 
Select ASP.NET Core Web Application and select API template as below.
 
Implementing Generic Repository And CRUD Operations In ASP.NET Core Web API
 
Create a new folder in Solution Explorer and name it as "Models" as following.
 
Implementing Generic Repository And CRUD Operations In ASP.NET Core Web API 
 
Add a new class in the Models folder by right-clicking on folder > Add > Class.
 
Name your class as Customer and add the following code in the class. 
  1. public class Customer  
  2. {  
  3.     [Key]  
  4.     [DatabaseGenerated(DatabaseGeneratedOption.Identity)]  
  5.     public int ID { getset; }  
  6.     public string Name { getset; }  
  7.     public string Email { getset; }  
  8.     public string Mobile { getset; }  
  9. }  
For implementing Generic Repository, we have to add an interface to define our generic functions.
 
Right-click on Models class and add an interface, name it as "IDataRepository", and add the following code.
  1. public interface IDataRepository<TEntity>  
  2. {  
  3.     IEnumerable<TEntity> GetAll();  
  4.     TEntity Get(int id);  
  5.     void Add(TEntity entity);  
  6.     void Change(TEntity dbEntity, TEntity entity);  
  7.     void Delete(TEntity entity);  
  8. }   
We have declared five methods for CRUD operations and these methods will be implemented in action classes of every model. 
 
Let's add an Actions class. Right-click on the Models folder and add a class name it as "CustomerManager" and add the following code in the class.
  1. public class CustomerManager : IDataRepository<Customer>  
  2. {  
  3.     readonly ResturantDbContext _resturantDb;  
  4.     public CustomerManager(ResturantDbContext context)  
  5.     {  
  6.         _resturantDb = context;  
  7.     }  
  8.   
  9.     public IEnumerable<Customer> GetAll()  
  10.     {  
  11.         return _resturantDb.Customers.ToList();  
  12.     }  
  13.   
  14.     public Customer Get(int id)  
  15.     {  
  16.         return _resturantDb.Customers  
  17.               .FirstOrDefault(e => e.ID == id);  
  18.     }  
  19.   
  20.     public void Add(Customer customer)  
  21.     {  
  22.         _resturantDb.Customers.Add(customer);  
  23.         _resturantDb.SaveChanges();  
  24.     }  
  25.   
  26.     public void Change(Customer customer, Customer entity)  
  27.     {  
  28.   
  29.         customer.Name = entity.Name;  
  30.         customer.Email = entity.Email;  
  31.         customer.Mobile = entity.Mobile;  
  32.   
  33.            _resturantDb.SaveChanges();  
  34.     }  
  35.   
  36.     public void Delete(Customer customer)  
  37.     {  
  38.         _resturantDb.Customers.Remove(customer);  
  39.         _resturantDb.SaveChanges();  
  40.     }  
  41. }   
The CustomerManager class in inherited by the IDataRepository interface and all the methods that we have defined in IDataRepository are implemented in this class for CRUD operations.
 
Now, let's add a class as our DbContext class. Right-click on the Models folder and add a new class.
 
Name it as ResturantDbContext and add the following code.
  1. public class ResturantDbContext:DbContext  
  2. {  
  3.     public ResturantDbContext(DbContextOptions<ResturantDbContext> options)   
  4.         : base(options)  
  5.     {  
  6.   
  7.     }  
  8.          
  9.     public DbSet<Customer> Customers { getset; }  
  10. }   
ResturantDbContext is inherited by DbContext class of EntityFrameworkCore. Add a new migration by witing the following command in Package-Manager Console.
  1. add-migration CustomerTable   
Press Enter. A new migration will be added to your Migrations folder. (If you do not have a Migrations folder, it will be added automatically), as below.
 
Implementing Generic Repository And CRUD Operations In ASP.NET Core Web API
 
Add the connection string as following in your appsetting.json file.
 
Implementing Generic Repository And CRUD Operations In ASP.NET Core Web API 
 
Run the following command in your Package-Manager Console to update the database.
  1. update-database   
By running the above command, the database will be generated and the table will be created in your database.
 
Implementing Generic Repository And CRUD Operations In ASP.NET Core Web API 
 
Now, for implementing CRUD operations, we have to add a Controller for Customer Class.
 
Right click on the Controllers folder and add a New Controller.
 
Name it as CustomersController and add the following code into it.
  1. public class CustomersController : Controller  
  2. {  
  3.     private IDataRepository<Customer> _repository;  
  4.     public CustomersController (IDataRepository<Customer> repository)  
  5.     {  
  6.         _repository = repository;  
  7.     }  
  8.   
  9.     // GET: api/<controller>  
  10.     [HttpGet]  
  11.     public IActionResult Get()  
  12.     {  
  13.         IEnumerable<Customer> customers = _repository.GetAll();  
  14.         return Ok(customers);  
  15.     }  
  16.   
  17.     // GET api/<controller>/5  
  18.     [HttpGet("{id}")]  
  19.     public IActionResult Get(int id)  
  20.     {  
  21.         Customer customer = _repository.Get(id);  
  22.   
  23.         if (customer == null)  
  24.         {  
  25.             return NotFound("The Employee record couldn't be found.");  
  26.         }  
  27.   
  28.         return Ok(customer);  
  29.     }  
  30.   
  31.     // POST api/<controller>  
  32.     [HttpPost]  
  33.     public IActionResult Post([FromBody]Customer customer)  
  34.     {  
  35.         if (customer == null)  
  36.         {  
  37.             return BadRequest("Customer is Null");  
  38.         }  
  39.         _repository.Add(customer);  
  40.         return CreatedAtRoute("Get"new { Id = customer.ID }, customer);  
  41.     }  
  42.   
  43.     // PUT api/<controller>/5  
  44.     [HttpPut("{id}")]  
  45.     public IActionResult Put(int id, [FromBody]Customer customer)  
  46.     {  
  47.         if (customer == null)  
  48.         {  
  49.             return BadRequest("Customer is null");  
  50.         }  
  51.         Customer customerToUpdate = _repository.Get(id);  
  52.         if (customerToUpdate == null)  
  53.         {  
  54.             return NotFound("Customer could not be found");  
  55.         }  
  56.         _repository.Change(customerToUpdate, customer);  
  57.         return NoContent();  
  58.     }  
  59.   
  60.     // DELETE api/<controller>/5  
  61.     [HttpDelete("{id}")]  
  62.     public IActionResult Delete(int id)  
  63.     {  
  64.         Customer customer = _repository.Get(id);  
  65.         if (customer == null)  
  66.         {  
  67.             return BadRequest("Customer is not found");  
  68.         }  
  69.         _repository.Delete(customer);  
  70.         return NoContent();  
  71.     }  
  72. }  
In this controller, we declared the instance of repository in line 3 and in <> braces, we entered customer to make it understand that all
methods will be used for Customer class. 
 
Add one or two entries in your database table.
 
Implementing Generic Repository And CRUD Operations In ASP.NET Core Web API
 
Run your project.
 
Handle the Get Request using POSTMAN.
 
Here is the result of our GET request.
 
Implementing Generic Repository And CRUD Operations In ASP.NET Core Web API
 
For handling all four CRUD requests using POSTMAN, you can use this link.
 
Happy Coding! 


Similar Articles