CRUD Operations Using ASP.NET Core 2.0 And In-Memory Database With Entity Framework

In this article, we will create a Web API with the in-memory database using Entity Framework and ASP.NET Core 2.0 without any theoretical explanation.

In this article, we will create a Web API with an in-memory database using Entity Framework and ASP.NET Core 2.0 without any theoretical explanation. To know more about concepts and theory, my previous articles can be referred to.

Let’s quickly create a new ASP.NET Core application by choosing API template and name it as ConferencePlanner. Add a new Model entity named Workshop inside a newly add Models folder as shown below,
  1. public class Workshop  
  2. {    
  3.     public int Id { getset; }  
  4.    
  5.     public string Name { getset; }  
  6.   
  7.     public string Speaker { getset; }  
  8.   
  9. }  

Here, we are going to use in-memory class along with EF. So, we have to add a new class for setting up the database context as shown below,

  1. public class ApplicationDbContext:DbContext  
  2. {  
  3.     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> context):base(context)  
  4.     {  
  5.   
  6.     }  
  7. }  

Now, we have to maintain multiple workshops under a conference. So, go ahead and add a DBSet in ApplicationContext class,

  1. public DbSet<Workshop> Workshops { getset; }   

Next, register the DBContext with our application. So, add the below code in Startup.cs class,

  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     services.AddMvc();  
  4.     services.AddDbContext<ApplicationDbContext>(context => { context.UseInMemoryDatabase("ConferencePlanner"); });  
  5.   
  6. }  

Now, we will add an Empty Controller using scaffolding options and name it as WorkshopController. Here, we also have to associate database context with this controller. So, let’s associate the database context as shown below with some dummy data in it.

  1. public class WorkshopController : Controller   
  2. {  
  3.     private ApplicationDbContext _context;   
  4.     public WorkshopController(ApplicationDbContext context)  
  5.     {  
  6.   
  7.       _context = context;  
  8.        if (!_context.Workshops.Any())   
  9.        {  
  10.          _context.Workshops.Add(new Workshop   
  11.                   { Name = "Event Management", Speaker = "Shweta"});  
  12.          _context.SaveChanges();   
  13.        }  
  14.     }  
  15. }  
Let's add our first method to get a list of all the workshops by adding the below code,
  1. [HttpGet]  
  2.  public IEnumerable<Workshop> GetWorkshops()  
  3.   {  
  4.           return _context.Workshops;  
  5.    }  
Now before proceeding further, let’s quickly build the application and run it. Verify that it is working fine as expected.
  1. [{"id":1,"name":"Event Management","speaker":"Shweta"}]  
Now, our base setup is ready. We can add the CRUD operations. Let’s go ahead and add these.
  1. [HttpPost]
  2. public IActionResult AddWorkshop(Workshop workshop)  
  3. {  
  4.        if (workshop == null)  
  5.             return BadRequest();  
  6.   
  7.        _context.Workshops.Add(workshop);  
  8.        _context.SaveChanges();  
  9.   
  10.        return CreatedAtRoute("GetWorkshops"new { id = workshop.Id }, workshop);  
  11. }  

In the above code snippet, CreateAtRoute() method is associating newly added workshop object to exiting list of workshops so,that it can be read by method GetWorkshops().

  1. [HttpPut("{id}")] // means that this id will come from route  
  2. public IActionResult UpdateWorkshopByID(int id, [FromBody]Workshop ws)  
  3. {  
  4.   
  5.     if (ws == null || ws.Id != id)  
  6.           return BadRequest();  
  7.   
  8.     var workshop = _context.Workshops.FirstOrDefault(i => i.Id == id);  
  9.     if (workshop == null)  
  10.           return NotFound();  
  11.   
  12.     workshop.Name = ws.Name;  
  13.     workshop.Speaker = ws.Speaker;  
  14.   
  15.     _context.Workshops.Update(workshop);  
  16.     _context.SaveChanges();  
  17.     return new NoContentResult();  
  18. }  
  19.   
  20. [HttpDelete]  
  21. public IActionResult DeleteWorkshopByID(int id)  
  22. {  
  23.     var workshop = _context.Workshops.FirstOrDefault(i => i.Id == id);  
  24.     if (workshop == null)  
  25.          return NotFound();  
  26.   
  27.     _context.Workshops.Remove(workshop);  
  28.     _context.SaveChanges();  
  29.   
  30.     return new NoContentResult();  
  31. }  

Hope you enjoyed learning CRUD operations.