Create, Edit And Delete API Using Entity Framework Core

Introduction

 
In this post we will learn about Create, Edit and Delete API using Entity Framework core. The below posts will help to understand the basics of Entity Framework core and application structure.
Step 1
 
All the basic steps are covered in the above posts. First we will add below methods in "IEmployeeRepository.cs" file. 
  1. void AddEmployeeAddress(int employeeId, Address address);  
  2. bool SaveDbChanges();  
Step 2
 
Implement these 2 methods in "EmployeeRepository.cs". 
  1.    public void AddEmployeeAddress(int employeeId, Address address)  
  2.       {  
  3.           var employee = GetEmployee(employeeId);  
  4.           employee.EmployeeAddress.Add(address);  
  5.       }  
  6.   
  7.       public bool SaveDbChanges()  
  8.       {  
  9.           return (_context.SaveChanges() >= 0);  
  10.       }  
Step 3
 
Now we will create and implement "CreateAddress" Method in "AddressController".
  • Line 01, we have added "HttpPost" attribute to add "Address" entity.
  • Line 08, we did the input mapping to "Address" entities.
  • Line 09,10, we have used the "AddEmployeeAddress" and "SaveDbChanges" method which we created in "EmployeeRepository.cs"
  • Line 11,we did the "Address" entities mapping back to "Address" DTO Model.
  • Line 12-15, in general we can return the created data(Address),so that we will display in API result. 
  1.      [HttpPost]  
  2.      public IActionResult CreateAddress(int employeeId, [FromBody] AddressModel address)  
  3.      {  
  4.          if (!_employeeRepository.IsEmployeeAvailable(employeeId))  
  5.          {  
  6.              return NotFound();  
  7.          }    
  8.          var addressData = _mapper.Map<Address>(address);    
  9.          _employeeRepository.AddEmployeeAddress(employeeId, addressData);  
  10.          _employeeRepository.SaveDbChanges();    
  11.          var addressToReturn = _mapper.Map<AddressModel>(addressData);    
  12.          return CreatedAtRoute(  
  13.              "GetEmployeeAddress",  
  14.              new { employeeId, Id = addressToReturn.Id },  
  15.              addressToReturn);  
  16.      }  
Step 4
 
In Postman, if we run the POST query with input body "AddressDetail", it's inserted in Db and returns the data.
 
Create, Edit And Delete API Using Entity Framework Core
 
Step 5
 
Before we update the "Address" data, first check the data in "GET" call. 
 
Create, Edit And Delete API Using Entity Framework Core
 
Step 6
 
We can't use the "AddressModel" which we used in "CreateAddress". We need to create below "AddresUpdateModel" without "Id" fields. 
  1. public class AddressUpdateModel  
  2.     {  
  3.         public string AddressDetail { getset; }         
  4.     }  
Step 7
 
We need add this "AddressUpdateModel" to "Address" db entities. Add the below line in "EmployeeMapper.cs" file. 
  1. CreateMap<AddressUpdateModel,Address>();  
Step 8
 
We will implement the update "UpdateAddress" method in "AddressController". We have used ""AddresUpdateModel" in input parameter and "HttpPut" Attribute.
  1. [HttpPut("{id}")]  
  2.         public IActionResult UpdateAddress(int employeeId, int id, [FromBody] AddressUpdateModel address)  
  3.         {  
  4.             if (!_employeeRepository.IsEmployeeAvailable(employeeId))  
  5.             {  
  6.                 return NotFound();  
  7.             }    
  8.             var employeeAddress = _employeeRepository.GetEmployeeAddress(employeeId, id);   
  9.             if (employeeAddress == null)  
  10.             {  
  11.                 return NotFound();  
  12.             }    
  13.             _mapper.Map(address, employeeAddress);    
  14.             _employeeRepository.UpdateAddress(employeeId, employeeAddress);  
  15.             _employeeRepository.SaveDbChanges();    
  16.             return NoContent();  
  17.         }  
Step 9
 
If we run the API in postman, the address details got updated as shown below. 
 
Create, Edit And Delete API Using Entity Framework Core
 
Step 10
 
We will add a new "Delete" method in "IEmployeeRepository" and then Impement in "EmployeeRepository" class.
 
In IEmployeeRepository,
  1. void DeleteAddress(Address address);  
In EmployeeRepository,
  1. public void DeleteAddress(Address address)  
  2.        {  
  3.            _context.Addresses.Remove(address);  
  4.        }  
Implement the method in "AddressController. 
  1. [HttpDelete("{id}")]  
  2.        public IActionResult DeleteAddress(int employeeId, int id)  
  3.        {  
  4.            if (!_employeeRepository.IsEmployeeAvailable(employeeId))  
  5.            {  
  6.                return NotFound();  
  7.            }    
  8.            var employeeAddress = _employeeRepository.GetEmployeeAddress(employeeId, id);   
  9.            if (employeeAddress == null)  
  10.            {  
  11.                return NotFound();  
  12.            }               
  13.            _employeeRepository.DeleteAddress(employeeAddress);  
  14.            _employeeRepository.SaveDbChanges();    
  15.            return NoContent();  
  16.        }  
Step 11
 
Now run the "DeleteAddress" from PostMan and we got the "204 No content" in the result. 
Create, Edit And Delete API Using Entity Framework Core
 
If we run the GET call for the deleted Address, we won't find it.
 
Create, Edit And Delete API Using Entity Framework Core
 
Step 12
 
I added below codes for your reference.
 
AddressController,
  1. [ApiController]  
  2.     [Route("api/employee/{employeeId}/address")]  
  3.     public class AddressController : ControllerBase  
  4.     {    
  5.         private readonly ILogger<EmployeeController> _logger;  
  6.         private readonly IEmployeeRepository _employeeRepository;  
  7.         private IMapper _mapper;  
  8.         public AddressController(ILogger<EmployeeController> logger, IEmployeeRepository employeeRepository, IMapper mapper)  
  9.         {  
  10.             _logger = logger;  
  11.             _employeeRepository = employeeRepository;  
  12.             _mapper = mapper;  
  13.         }    
  14.         // GET: api/<controller>  
  15.         [HttpGet]  
  16.         public IActionResult GetAllAddress(int employeeId)  
  17.         {    
  18.             if (!_employeeRepository.IsEmployeeAvailable(employeeId))  
  19.             {  
  20.                 return NotFound();  
  21.             }  
  22.             var addressData = _employeeRepository.GetAddress(employeeId);    
  23.             if (addressData == null)  
  24.             {  
  25.                 return NotFound();  
  26.             }    
  27.             return Ok(_mapper.Map<IEnumerable<Address>>(addressData));  
  28.         }   
  29.   
  30.         [HttpGet("{id}", Name = "GetEmployeeAddress")]  
  31.         public IActionResult GetEmployeeAddress(int employeeId, int id)  
  32.         {  
  33.             if (!_employeeRepository.IsEmployeeAvailable(employeeId))  
  34.             {  
  35.                 return NotFound();  
  36.             }    
  37.             var address = _employeeRepository.GetEmployeeAddress(employeeId, id);   
  38.             if (address == null)  
  39.             {  
  40.                 return NotFound();  
  41.             }    
  42.             return Ok(_mapper.Map<Address>(address));  
  43.         }  
  44.   
  45.         [HttpPost]  
  46.         public IActionResult CreateAddress(int employeeId, [FromBody] AddressModel address)  
  47.         {  
  48.             if (!_employeeRepository.IsEmployeeAvailable(employeeId))  
  49.             {  
  50.                 return NotFound();  
  51.             }    
  52.             var addressData = _mapper.Map<Address>(address);    
  53.             _employeeRepository.AddEmployeeAddress(employeeId, addressData);  
  54.             _employeeRepository.SaveDbChanges();    
  55.             var addressToReturn = _mapper.Map<AddressModel>(addressData);   
  56.             return CreatedAtRoute(  
  57.                 "GetEmployeeAddress",  
  58.                 new { employeeId, Id = addressToReturn.Id },  
  59.                 addressToReturn);  
  60.         }  
  61.   
  62.         [HttpPut("{id}")]  
  63.         public IActionResult UpdateAddress(int employeeId, int id, [FromBody] AddressUpdateModel address)  
  64.         {  
  65.             if (!_employeeRepository.IsEmployeeAvailable(employeeId))  
  66.             {  
  67.                 return NotFound();  
  68.             }    
  69.             var employeeAddress = _employeeRepository.GetEmployeeAddress(employeeId, id);   
  70.             if (employeeAddress == null)  
  71.             {  
  72.                 return NotFound();  
  73.             }    
  74.             _mapper.Map(address, employeeAddress);    
  75.             _employeeRepository.UpdateAddress(employeeId, employeeAddress);  
  76.             _employeeRepository.SaveDbChanges();   
  77.             return NoContent();  
  78.         }  
  79.   
  80.         [HttpDelete("{id}")]  
  81.         public IActionResult DeleteAddress(int employeeId, int id)  
  82.         {  
  83.             if (!_employeeRepository.IsEmployeeAvailable(employeeId))  
  84.             {  
  85.                 return NotFound();  
  86.             }    
  87.             var employeeAddress = _employeeRepository.GetEmployeeAddress(employeeId, id);   
  88.             if (employeeAddress == null)  
  89.             {  
  90.                 return NotFound();  
  91.             }                
  92.             _employeeRepository.DeleteAddress(employeeAddress);  
  93.             _employeeRepository.SaveDbChanges();    
  94.             return NoContent();  
  95.         }    
  96.     }  
EmployeeRepository,
  1. public class EmployeeRepository : IEmployeeRepository  
  2.     {  
  3.         private readonly EmployeeDbContext _context;  
  4.         public EmployeeRepository(EmployeeDbContext context)  
  5.         {  
  6.             _context = context;  
  7.         }    
  8.         public void AddEmployeeAddress(int employeeId, Address address)  
  9.         {  
  10.             var employee = GetEmployee(employeeId);    
  11.             employee.EmployeeAddress.Add(address);    
  12.         }    
  13.         public bool SaveDbChanges()  
  14.         {  
  15.             return (_context.SaveChanges() >= 0);  
  16.         }    
  17.         public void UpdateAddress(int employeeId, Address address)  
  18.         {  
  19.             //var employee = GetEmployee(employeeId);    
  20.             //employee.EmployeeAddress.Add(address);  
  21.         }    
  22.         public void DeleteAddress(Address address)  
  23.         {  
  24.             _context.Addresses.Remove(address);  
  25.         }    
  26.         public IEnumerable<Employee> GetAllEmployee()  
  27.         {  
  28.             return _context.Employees.OrderBy(e => e.EmployeeName).ToList();  
  29.         }    
  30.         public Employee GetEmployee(int employeeId, bool isWithAddress=false)  
  31.         {  
  32.             if (isWithAddress)  
  33.             {  
  34.                 return _context.Employees.Include(e => e.EmployeeAddress)  
  35.                             .Where(a => a.Id == employeeId).FirstOrDefault();  
  36.             }  
  37.               return _context.Employees.Where(e => e.Id==employeeId).FirstOrDefault();  
  38.         }    
  39.         public Address GetEmployeeAddress(int employeeId, int addressId)  
  40.         {  
  41.             return _context.Addresses.Where(a => a.Id == addressId  
  42.                                         && a.EmployeeId == employeeId).FirstOrDefault();  
  43.         }  
  44.         public IEnumerable<Address> GetAddress(int employeeId)  
  45.         {  
  46.             return _context.Addresses.Where(a => a.EmployeeId == employeeId).ToList();  
  47.         }    
  48.         public bool IsEmployeeAvailable(int employeeId)  
  49.         {  
  50.             return _context.Employees.Any(e => e.Id == employeeId);  
  51.         }            
  52.     }  

Summary

 
In this post we learned to create, update and delete API resources using "Entity Framwork Core". You can also check the previous "Entitiy Framework Core" posts from the below links.


Similar Articles