CRUD Operation With .NET Core 3.1 And Entity Framework Core

In this article I am going to walk you through CRUD operation using .net core 3.1 and entity framework core and SQL Server to store data. Here I will explain step by step how to Create, Read, Update and Delete employees from sql table using Rest API, EntityFramework core and sql server.
 
Before starting this there are a few prerequisites as below,
  1. Visual Studio 2019
  2. SQL server 2017
  3. .Net core 3.1
  4. Entity Framework core
  5. PostMan to test rest api. 
Let's start with Visual Studio to create Rest API endpoint for Create, Read, Update and Delete method using core api 3.1.
  1. Start Visual Studio 2019 and click create a new project from the below screen. 
  • Once you  click on a new project you will get a new screen to select Asp .Net Core Web Application from the below screen and click on next button. 
 
  • After clicking on the next button give a project name and location for your project where you want to save your project. 
 
  • Now we have the option to select framework and framework version as in the below screen, I have selected core and version core 3.1.
 
  • After selecting the above option click on create. You are done with you new project for Rest API Core 3.1.
 
  • Once you are done with new core api project, you will get default controller with Weatherforcast as below. 
 
  • Once you build your application then you should get the below screen by default. If you are getting the below screen then your solution is up and running.
  • Now let's start with SQL server script to create table in database.
    1. CREATE TABLE [dbo].[Employees](      
    2.     [Id] [int] IDENTITY(1,1) NOT NULL,      
    3.     [FirstName] [varchar](50) NOT NULL,    
    4.     [LastName] [varchar](50) NOT NULL,       
    5.     [Email] [varchar](50) NOT NULL,    
    6.     [City] [varchar](50) NOT NULL,      
    7.     [Salary] [intNOT NULL,      
    8. PRIMARY KEY CLUSTERED       
    9. (      
    10.     [Id] ASC      
    11. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]      
    12. ON [PRIMARY]     
  • Now let's create new folder as Model and add new class with name Employee under Model folder,
    1. using System.ComponentModel.DataAnnotations;    
    2.     
    3. namespace RestAPICoreDemo.Model    
    4. {    
    5.         
    6.     public class Employee    
    7.     {    
    8.         [Key]    
    9.         public int Id { getset; }    
    10.         public string FirstName { getset; }    
    11.         public string LastName { getset; }    
    12.         public string Email { getset; }    
    13.         public string City { getset; }    
    14.         public int Salary { getset; }    
    15.     
    16.     }    
    17. }    
  • Now add EntityFrameworkCore package from nuget package manger. Install packages for Entity framework core
  • Microsoft.EntityFrameworkCore.SqlServer
 
  • Let's creat EmployeeContext which is used to communicate with database and help us to do operations like Create, Read, Update and Delete operation for our table.
    1. using Microsoft.EntityFrameworkCore;    
    2. using RestAPICoreDemo.Model;    
    3.     
    4. namespace RestAPICoreDemo    
    5. {    
    6.     public class EmployeeContext : DbContext    
    7.     {    
    8.         public EmployeeContext(DbContextOptions<EmployeeContext> options) : base(options)    
    9.         {    
    10.     
    11.         }    
    12.     
    13.         public DbSet<Employee> Employees { getset; }    
    14.     }    
    15. }    
  • Let's create Employee service to perform all operation like Create, Read, Update and Delete operations. Add Service contract using interface and implement same interface using employee service.
  • Add service contract in Employee service interface
IEmployeeService.cs
  1. using RestAPICoreDemo.Model;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace RestAPICoreDemo.Service  
  5. {  
  6.     public interface IEmployeeService  
  7.     {  
  8.   
  9.         Employee AddEmployee(Employee employee);  
  10.   
  11.         List<Employee> GetEmployees();  
  12.   
  13.         void UpdateEmployee(Employee employee);  
  14.   
  15.         void DeleteEmployee(int Id);  
  16.   
  17.         Employee GetEmployee(int Id);  
  18.     }  
  19. }  
EmployeeService.cs
  1. using RestAPICoreDemo.Model;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4.   
  5. namespace RestAPICoreDemo.Service  
  6. {  
  7.     public class EmployeeService : IEmployeeService  
  8.     {  
  9.         public EmployeeContext _employeeDbContext;  
  10.         public EmployeeService(EmployeeContext employeeDbContext)  
  11.         {  
  12.             _employeeDbContext = employeeDbContext;  
  13.         }  
  14.         public Employee AddEmployee(Employee employee)  
  15.         {  
  16.             _employeeDbContext.Employees.Add(employee);  
  17.             _employeeDbContext.SaveChanges();  
  18.             return employee;  
  19.         }  
  20.         public List<Employee> GetEmployees()  
  21.         {  
  22.             return _employeeDbContext.Employees.ToList();  
  23.         }  
  24.   
  25.         public void UpdateEmployee(Employee employee)  
  26.         {  
  27.             _employeeDbContext.Employees.Update(employee);  
  28.             _employeeDbContext.SaveChanges();  
  29.         }  
  30.   
  31.         public void DeleteEmployee(int Id)  
  32.         {  
  33.             var employee = _employeeDbContext.Employees.FirstOrDefault(x => x.Id == Id);  
  34.             if (employee != null)  
  35.             {  
  36.                 _employeeDbContext.Remove(employee);  
  37.                 _employeeDbContext.SaveChanges();  
  38.             }  
  39.         }  
  40.   
  41.         public Employee GetEmployee(int Id)  
  42.         {  
  43.             return _employeeDbContext.Employees.FirstOrDefault(x => x.Id == Id);  
  44.         }  
  45.   
  46.     }  
  47.  
  • EmployeeController
  1. using System.Collections.Generic;  
  2. using Microsoft.AspNetCore.Mvc;  
  3. using RestAPICoreDemo.Model;  
  4. using RestAPICoreDemo.Service;  
  5.   
  6. namespace RestAPICoreDemo.Controllers  
  7. {  
  8.     [Route("api/[controller]")]  
  9.     [ApiController]  
  10.     public class EmployeeController : ControllerBase  
  11.     {  
  12.         private readonly IEmployeeService _employeeService;  
  13.         public EmployeeController(IEmployeeService employeeService)  
  14.         {  
  15.             _employeeService = employeeService;  
  16.         }  
  17.   
  18.         [HttpGet]  
  19.         [Route("[action]")]  
  20.         [Route("api/Employee/GetEmployees")]  
  21.         public IEnumerable<Employee> GetEmployees()  
  22.         {  
  23.             return _employeeService.GetEmployees();  
  24.         }  
  25.   
  26.         [HttpPost]  
  27.         [Route("[action]")]  
  28.         [Route("api/Employee/AddEmployee")]  
  29.         public IActionResult AddEmployee(Employee employee)  
  30.         {  
  31.             _employeeService.AddEmployee(employee);  
  32.             return Ok();  
  33.         }  
  34.   
  35.         [HttpPost]  
  36.         [Route("[action]")]  
  37.         [Route("api/Employee/UpdateEmployee")]  
  38.         public IActionResult UpdateEmployee(Employee employee)  
  39.         {  
  40.             _employeeService.UpdateEmployee(employee);  
  41.             return Ok();  
  42.         }  
  43.   
  44.         [HttpDelete]  
  45.         [Route("[action]")]  
  46.         [Route("api/Employee/DeleteEmployee")]  
  47.         public IActionResult DeleteEmployee(int id)  
  48.         {  
  49.             var existingEmployee = _employeeService.GetEmployee(id);  
  50.             if (existingEmployee != null)  
  51.             {  
  52.                 _employeeService.DeleteEmployee(existingEmployee.Id);  
  53.                 return Ok();  
  54.             }  
  55.             return NotFound($"Employee Not Found with ID : {existingEmployee.Id}");  
  56.         }  
  57.   
  58.         [HttpGet]  
  59.         [Route("GetEmployee")]  
  60.         public Employee GetEmployee(int id)  
  61.         {  
  62.             return _employeeService.GetEmployee(id);  
  63.         }  
  64.   
  65.     }  
  66. }  
  • We are done with service contract and implementation for all methods. 
  • Now need for dependency for employee service and Connection string in start up class file.
    1. public void ConfigureServices(IServiceCollection services)    
    2. {    
    3.     services.AddControllers();    
    4.     services.AddDbContextPool<EmployeeContext>(options =>     
    5.     options.UseSqlServer(Configuration.GetConnectionString("EmployeeDBContextConnectionString")));    
    6.      services.AddScoped<IEmployeeService, EmployeeService>();    
    7. }    
  • Now we are ready with all required changes, let's build and run our Web API solution.
  • Use Postman to test our API CRUD operation.
  • Let's check our SQL Table with select statement. Initially there will not be any records in Employee table.
 
  • Now open Postman and create new employee using "api/Employee/AddEmployee" end point.
 
 
  • Read Employee using "api/Employee/GetEmployees" end point.
  • Update Employee "api/Employee/UpdateEmployee" using end point.
  • Let's check updated employee using "api/Employee/GetEmployee" endpoint which should return employee details with updated data as below.
 
  • Delete Employee "api/Employee/DeleteEmployee" using end point which should retunr status code 200 with Ok. It means deleted employee from table.
  • Let's check the same employee using "api/Employee/GetEmployee" by passing employee id. Now it should return status code 204 No Content. It means employee is sucessfully deleted using delete endpoint.
 
  • Let's finally check in SQL table there will be no records as we deleted employee using delete endpoint.
 
  • At last I am submitting a few records using "api/Employee/AddEmployee" endpoint and then will fetch all employees using "api/Employee/GetEmployees" 
 
 
  • Finally I am going to verify these records in sql server table using select query and it shoud return all records. 
 
 

Summary

 
In this article we have learned how to build CRUD operation using .net core 3.1, entityframework core, sql server and used postman for testing all end points. I hope you have enjoyed this article. Thank you for your time and always feel free to reeach out to me in case you have any queries. Please find my other article at this link My Articles