ASP.NET Core CRUD API Using Entity Framework

Introduction

 
In my last article, we discussed the basics of ASP.NET Core APIs and how to create an API using Entity Framework. Finally, we ended up with creating a Get API which is used to fetch the details of all the authors from the back-end as a list. Now, in this article, we are going to see how to create a CRUD (Create, Read, Update, Delete) API in ASP.NET Core.
 
This is a continuation of my last article (create RESTful API using ASP.NET Core with Entity Framework Core), so I highly recommend you to go through my previous article for the basic set up of an ASP.NET Core application.
 

CREATE

 
I’m using my existing application that we created in my last article for a demo. Open the LibraryRepository.cs file from the application and write the below code.
  1. public Author PostAuthor(Author author)  
  2.       {  
  3.           try  
  4.           {  
  5.               if(_libraryContext!=null)  
  6.               {  
  7.                   _libraryContext.Add(author);  
  8.                   _libraryContext.SaveChanges();  
  9.                   return author;  
  10.               }  
  11.               else  
  12.               {  
  13.                   return null;  
  14.               }  
  15.           }  
  16.           catch(Exception ex)  
  17.           {  
  18.               //log exception  
  19.               return null;  
  20.           }  
  21.       }  
_libraryContext is our database context, the Add method is used to add the records in the entity, the SaveChanges method is used to save the changes in the database.
 
Open LibrariesController.cs file from the application and write this code.
  1. [HttpPost]  
  2.        [Route("AddAuthor")]  
  3.        public IActionResult AddAuthor([FromBody]Author authorparam)  
  4.        {  
  5.            try  
  6.            {  
  7.                if (ModelState.IsValid)  
  8.                {  
  9.                    Author author = _libraryRepository.PostAuthor(authorparam);  
  10.                    return Ok(author);  
  11.                }  
  12.                else  
  13.                {  
  14.                    return BadRequest();  
  15.                }  
  16.            }  
  17.            catch  
  18.            {  
  19.                //log Exception  
  20.                return BadRequest();  
  21.            }  
  22.        }  

The AddAuthor action will fetch the data from the body of request. Once the modelstate is validated, the data will be added to the database by calling the PostAuthor method in repository.

Let’s test the API in POSTMAN.

https://localhost:44348/api/Libraries/AddAuthor

ASP.NET Core CRUD API's Using Entity Framework 
 
From the above image, you can notice that the data is successfully added and returned.
 
Changes in the database.
 
ASP.NET Core CRUD API's Using Entity Framework 
 

READ

 
We already discussed about GetAllAuthor() read method in my last article. Now, I’m giving a demo of the method which is used to read the data from the database based on Id.
 
Open the LibraryReporsitory.cs file from the application and write the following code into it.
  1. public Author GetAuthor(Guid authorId)  
  2.         {  
  3.             try  
  4.             {  
  5.                 return _libraryContext.Authors.Where(e => e.AuthorId == authorId).FirstOrDefault();  
  6.             }  
  7.             catch(Exception ex)  
  8.             {  
  9.                 //log exception  
  10.                 return null;  
  11.             }  
  12.         }  
Open the LibrariesController.cs file from the application to add the below code.
  1. [HttpGet]  
  2.      [Route("GetAuthor")]  
  3.   
  4.      public IActionResult GetAuthor(Guid authorId)  
  5.      {  
  6.          try  
  7.          {  
  8.              Author author = _libraryRepository.GetAuthor(authorId);  
  9.              return Ok(author);  
  10.          }  
  11.          catch(Exception ex)  
  12.          {  
  13.              //log exception   
  14.              return BadRequest();  
  15.          }  
  16.      }  

Let’s test the API in POSTMAN.

https://localhost:44348/api/Libraries/DeleteAuthor?authorId=04dcc177-9a0a-4444-4aff-08d694b67230

 ASP.NET Core CRUD API's Using Entity Framework
 
From the above image, you can notice the author data is returned based on the author id.
 

UPDATE

 
Open LibraryRepository.cs file and update it with the given code. 
  1. public Author UpdateAuthor(Author author)  
  2.      {  
  3.          try  
  4.          {  
  5.              if (_libraryContext != null)  
  6.              {  
  7.                  _libraryContext.Update(author);  
  8.                  _libraryContext.SaveChanges();  
  9.                  return author;  
  10.              }  
  11.              else  
  12.              {  
  13.                  return null;  
  14.              }  
  15.          }  
  16.          catch (Exception ex)  
  17.          {  
  18.              //log exception  
  19.              return null;  
  20.          }  
  21.      }   
_libraryContext is our database context, the Update method is used to update the records in the entity, the SaveChanges method is used to save the changes in the database.
 
Open LibrariesController.cs file from the application and write the below code.
  1. [HttpPut]  
  2.       [Route("UpdateAuthor")]  
  3.       public IActionResult UpdateAuthor([FromBody]Author authorparam)  
  4.       {  
  5.           try  
  6.           {  
  7.               if (ModelState.IsValid)  
  8.               {  
  9.                   Author author = _libraryRepository.UpdateAuthor(authorparam);  
  10.                   return Ok(author);  
  11.               }  
  12.               else  
  13.               {  
  14.   
  15.                   return BadRequest();  
  16.               }  
  17.           }  
  18.           catch(Exception ex)  
  19.           {  
  20.               //log Exception  
  21.               return BadRequest();  
  22.           }  
  23.       }  
The UpdateAuthor action will fetch the data from the body of request. Once the modelstate is validated, the data will be updated in database by calling the UpdateAuthor method in the repository.
 
Let’s test the API in POSTMAN.
 
https://localhost:44348/api/Libraries/UpdateAuthor
 
ASP.NET Core CRUD API's Using Entity Framework
 
From the above image, you can notice that the author data is updated based on the request.
 
Changes in the database
 
ASP.NET Core CRUD API's Using Entity Framework 
 

DELETE

 
Open the LibraryRepository.cs file from the application and add the following code.
  1. public int DeleteAuthor(Guid authorId)  
  2.  {  
  3.      try  
  4.      {  
  5.          if (_libraryContext != null)  
  6.          {  
  7.              var author = _libraryContext.Authors.FirstOrDefault(x => x.AuthorId== authorId);  
  8.              if(author!=null)  
  9.              {  
  10.                  _libraryContext.Remove(author);  
  11.                  return 1;  
  12.              }  
  13.              else  
  14.              {  
  15.                  return 0;  
  16.              }  
  17.          }  
  18.          else  
  19.          {  
  20.              return 0;  
  21.          }  
  22.   
  23.   
  24.      }  
  25.      catch(Exception ex)  
  26.      {  
  27.          //log exception  
  28.          return 0;  
  29.      }  
  30.  }  
The Remove method is used to remove the records in the entity, the SaveChanges method is used to save the changes in the database based on update done in data entity.
 
Open LibrariesController.cs file from the application and write this code.
  1. [HttpDelete]  
  2.         [Route("DeleteAuthor")]  
  3.         public IActionResult DeleteAuthor(Guid authorId)  
  4.         {  
  5.             try  
  6.             {  
  7.                 int result = _libraryRepository.DeleteAuthor(authorId);  
  8.                 return Ok(result);  
  9.             }  
  10.             catch(Exception ex)  
  11.             {  
  12.                 //log Exception  
  13.                 return BadRequest();  
  14.             }  
  15.         }  
The DeleteAuthor method will delete the record by calling the DeleterAuthor method in the repository based on the author id passed through the request.
 
Let’s test the API in POSTMAN.
 
https://localhost:44348/api/Libraries/DeleteAuthor?authorId=04dcc177-9a0a-4444-4aff-08d694b67230
 
ASP.NET Core CRUD API's Using Entity Framework
 
From the above image, you can notice that we got a response as 1 which means the data is deleted successfully based on the request. Click here to get the source code. 
 

Conclusion

 
Today, we saw how to create a CRUD API in ASP.NET Core with Entity Framework. We will see more about ASP.NET Core in my future articles.