Performing CRUD Operations With ASP.NET MVC Core And Entity Framework Core

Introduction

ASP.NET Core is a significant redesign of ASP.NET. It is an open source, cross-platform framework to develop Cloud based applications like web applications, IoT applications, and mobile back-end applications. We can develop and run the ASP.NET Core application on multiple (cross) platforms, such as Windows, Mac OS, and Linux. Entity Framework Core is a lightweight and extensible version of Entity Framework. It is based on ORM (Object-Relational Mapper) which enables us to work with databases using .NET objects.

In this article, we will learn how to perform CRUD (Create, Read, Update and Delete) operations in ASP.net Core MVC, using Entity Framework Core. Here, I have used the  "Code First" approach for developing Entity model and as a development tool, I am using "Visual Studio Code". Here, I am doing manual database migration.

To use Entity Framework and MVC, we need to include certain references in project.json file. The following highlighted references need to be included.

  1. {  
  2.   "version""1.0.0-*",  
  3.   "buildOptions": {  
  4.     "preserveCompilationContext"true,  
  5.     "debugType""portable",  
  6.     "emitEntryPoint"true  
  7.   },  
  8.   "dependencies": {},  
  9.   "frameworks": {  
  10.     "netcoreapp1.0": {  
  11.       "dependencies": {  
  12.         "Microsoft.NETCore.App": {  
  13.           "type""platform",  
  14.           "version""1.0.1"  
  15.         },  
  16.         "Microsoft.EntityFrameworkCore.SqlServer" : "1.0.0",  
  17.         "Microsoft.EntityFrameworkCore.SqlServer.Design" : "1.0.0",  
  18.         "Microsoft.AspNetCore.Server.Kestrel""1.0.0",  
  19.         "Microsoft.AspNetCore.Mvc""1.0.0",  
  20.         "Microsoft.AspNetCore.Mvc.Formatters.Xml":"1.0.0",  
  21.         "Microsoft.Framework.Configuration.Json":"1.0.0-beta7"  
  22.       },  
  23.       "imports": [  
  24.         "dnxcore50",  
  25.         "portable-net452+win81"  
  26.       ]  
  27.     }  
  28.   }  
  29. }  
I have created “TestTables” table in database. It has three columns - Id, Name,  and Description. Id is primary key and auto-incremented.
  1. CREATE TABLE [dbo].[TestTables](  
  2.     [Id] [intNOT NULL Identity(1,1),  
  3.     [Name] [varchar](50) NULL,  
  4.     [Description] [varchar](50) NULL,  
  5.  CONSTRAINT [PK_TestTable] PRIMARY KEY CLUSTERED   
  6. (  
  7.     [Id] ASC  
  8. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  9. ON [PRIMARY]  
The next step is to create Entity model and TestTable entity.

EntityMoidel.cs
  1. using Microsoft.EntityFrameworkCore;  
  2. namespace WebApplication  
  3. {  
  4.     public class EntityModelContext : DbContext  
  5.     {  
  6.             public DbSet<TestTable> TestTables { get; set; }  
  7.     }  
  8. }  
TestTable.cs
  1. namespace WebApplication  
  2. {  
  3.     public class TestTable  
  4.     {  
  5.         public int Id { get; set; }  
  6.         public string Name { get; set; }  
  7.         public string Description { get; set; }  
  8.     }  
  9. }  
Now, I am adding "appsettings.json" file which holds various settings for the application. I have added database connection string in this file.

appsettings.json
  1. {    
  2.   "ConnectionStrings": {   
  3.     "DefaultConnection""Data Source=10.124.130.116;Initial Catalog=TestDB;User ID=sa; Password=Passwd@12"    
  4.   },    
  5.   "Logging": {    
  6.     "IncludeScopes"false,    
  7.     "LogLevel": {    
  8.       "Default""Debug",    
  9.       "System""Information",    
  10.       "Microsoft""Information"    
  11.     }    
  12.   }    
  13. }  
Startup.cs file is used to register services and injection of modules in HTTP pipeline. It has Startup class which is triggered when application launches the first time. This is same as Application_Start() event of global.asax file.

In this file, I have registered various services, like MVC, EF etc. Also, configure some global settings, like assigning connection string to dbcontext.

Startup.cs
  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Http;  
  3. using Microsoft.EntityFrameworkCore;  
  4. using Microsoft.AspNetCore.Hosting;  
  5. using Microsoft.Framework.Configuration;  
  6. using Microsoft.Extensions.DependencyInjection;  
  7. using System.IO;  
  8. using Microsoft.EntityFrameworkCore.Infrastructure;  
  9.   
  10. namespace WebApplication  
  11. {  
  12.     public class Startup  
  13.     {  
  14.         public void ConfigureServices(IServiceCollection services)  
  15.         {  
  16.             var builder = new ConfigurationBuilder(Directory.GetCurrentDirectory())  
  17.                       .AddJsonFile("appsettings.json");  
  18.                         
  19.             var configuration = builder.Build();  
  20.   
  21.             services.AddMvc();  
  22.             services.AddEntityFramework()  
  23.             .AddDbContext<EntityModelContext>(  
  24.                 options => options.UseSqlServer(configuration["ConnectionStrings:DefaultConnection"]));  
  25.         }  
  26.   
  27.         public void Configure(IApplicationBuilder app)  
  28.         {  
  29.             app.UseMvc();  
  30.   
  31.             app.Run(context =>  
  32.             {  
  33.                 return context.Response.WriteAsync("");  
  34.             });  
  35.         }  
  36.     }  
  37. }  
Creating Application User Interface

The next step is to create UI. In this step, I have created Controller and various required View. I have “HomeController.cs” file under the Controllers folder and created two Views under the “Views” folder. Following snap is showing the hierarchy of folders and files within our project.



Following is the code snippet for HomeController.

HomeController.cs

  1. using Microsoft.AspNetCore.Mvc;  
  2. using System.Linq;  
  3. using System.Collections.Generic;  
  4.   
  5. namespace WebApplication  
  6. {  
  7.     public class HomeController : Controller  
  8.     {  
  9.         private EntityModelContext _context=null;  
  10.         public HomeController(EntityModelContext context)  
  11.         {  
  12.             _context = context;  
  13.         }  
  14.   
  15.         [Route("home/index")]  
  16.         public IActionResult Index()  
  17.         {  
  18.             List<TestTable> data = null;  
  19.             data = _context.TestTables.ToList();  
  20.             return View(data);  
  21.         }  
  22.           
  23.         [Route("home/edit/{id?}")]  
  24.         [HttpGet]  
  25.         public IActionResult Edit(int? id)  
  26.         {  
  27.             TestTable data = new TestTable();  
  28.             if(id.HasValue)  
  29.             {  
  30.                 data = _context.TestTables.Where(p=>p.Id==id.Value).FirstOrDefault();  
  31.                 if(data==null)  
  32.                 {  
  33.                     data = new TestTable();  
  34.                 }  
  35.                 return View("Edit",data);  
  36.             }  
  37.             return View("Edit",data);  
  38.         }  
  39.   
  40.         [Route("home/post")]  
  41.         [HttpPost]  
  42.         public IActionResult Post(TestTable test)  
  43.         {  
  44.             if(test != null)  
  45.             {  
  46.                 bool isNew = false;  
  47.                 var data = _context.TestTables.Where(p=>p.Id==test.Id).FirstOrDefault();  
  48.                 if(data == null)  
  49.                 {  
  50.                     data = new TestTable();  
  51.                     isNew = true;  
  52.                 }  
  53.                 data.Name = test.Name;  
  54.                 data.Description = test.Description;  
  55.                 if(isNew)  
  56.                 {  
  57.                     _context.Add(data);  
  58.                 }  
  59.                 _context.SaveChanges();  
  60.             }  
  61.            return RedirectToAction("Index");  
  62.         }  
  63.         [Route("home/delete/{id}")]  
  64.         [HttpGet]    
  65.         public IActionResult Delete(int id)    
  66.         {    
  67.             TestTable data = _context.Set<TestTable>().FirstOrDefault(c => c.Id == id);    
  68.             _context.Entry(data).State = Microsoft.EntityFrameworkCore.EntityState.Deleted;    
  69.             _context.SaveChanges();    
  70.             return RedirectToAction("Index");    
  71.         }    
  72.   
  73.     }  
  74. }  
Index view (Initial List View)

It is the entry point of the application. Following is the code snippet for index View.

Index.cshtml
  1. @model IEnumerable<WebApplication.TestTable>    
  2. @using WebApplication;  
  3. <table >  
  4.     <thead>  
  5.         <tr>  
  6.             <th>Id</th>                        
  7.             <th>Name</th>    
  8.             <th>Description</th>  
  9.             <th></th>   
  10.             <th></th>   
  11.         </tr>   
  12.     </thead>  
  13.     <tbody>    
  14.           @foreach (var item in Model)    
  15.           {  
  16.               <tr>  
  17.                   <td>@item.Id</td>  
  18.                   <td>@item.Name</td>  
  19.                   <td>@item.Description</td>  
  20.                   <td>@Html.ActionLink("Edit""Edit"new { Id = @item.Id })</td>  
  21.                   <td>@Html.ActionLink("Delete""Delete"new { Id = @item.Id }, new { onclick="return confirm(Are you want to delete record?');" } )</td>  
  22.               </tr>    
  23.           }  
  24.     </tbody>  
  25. </table>  
  26. <br/>  
  27. @Html.ActionLink("Add Item""Edit"new { Id = 0})  
When we run this application, we might observe the following error. It is related to Entity Framework and tells us that database provider has not been configured.



“No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions<TContext> object in its constructor and passes it to the base constructor for DbContext”

The solution for this error is hidden in the message itself. This message tells us to add a new constructor to our DbContext, which will accept DbContextOption as parameter.

EntityModelContext.cs
  1. public class EntityModelContext : DbContext  
  2. {  
  3.      
  4.         public EntityModelContext(DbContextOptions<EntityModelContext> options) : base(options)  
  5.         {  
  6.   
  7.         }  
  8.         …..  
  9.         …..  
  10. }  
Now, I am re-running the application. No such error prompts this time and it is running successfully.

Output



Create add /edit/delete view

Now, I am defining the "Add/Edit" View. The following is the code snippet for "edit.cshtml".

Edit.cshtml
  1. @model WebApplication.TestTable    
  2. @using WebApplication;  
  3.   
  4. @using (Html.BeginForm("Post""Home", FormMethod.Post, new { }))    
  5. {    
  6.     @Html.ValidationSummary(true)    
  7.         
  8.     <fieldset>    
  9.         <legend></legend>    
  10.         <div class="editor-label">    
  11.            ID    
  12.         </div>    
  13.         <div class="editor-field">    
  14.             @Html.TextBoxFor(model => model.Id, new { @readonly = "readonly"} )    
  15.         </div>    
  16.         <div class="editor-label">    
  17.            Name    
  18.         </div>    
  19.         <div class="editor-field">    
  20.             @Html.TextBoxFor(model => model.Name)    
  21.             @Html.ValidationMessageFor(model => model.Name)    
  22.         </div>   
  23.         <div class="editor-label">    
  24.            Description    
  25.         </div>  
  26.         <div class="editor-field">    
  27.             @Html.TextBoxFor(model => model.Description)    
  28.             @Html.ValidationMessageFor(model => model.Description)    
  29.         </div>     
  30.     
  31.         <p>    
  32.             <input type="submit" value="Update" id="btnsave"  />    
  33.         </p>    
  34.     </fieldset>    
  35. }    
  36. <div>    
  37.     @Html.ActionLink("Close""Index")    
  38. </div>   
Output



At the time of deleting items, the system will ask for conformation. And if the user clicks on “Ok” button, system will delete the record from database.

Delete conformation



Conclusion

This article gave us the insights of CRUD operations in ASP.NET Core MVC, using Entity Framework Core. In the example, I have used simple form post method to perform the CRUD operations.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now