ASP.NET 5 CRUD Using Scaffolding And Entity Framework

Introduction

Both ASP.NET 5 and ASP.NET Core 1.0 are the same. Now, ASP.NET 5 is called ASP.NET Core 1.0, so in this article we will be using ASP.NET Core 1.0.

What is Scaffolding?

CRUD is very easy and simple using Scaffolding. Yes, Scaffolding will automatically generate code on the controller and view for performing our CRUD operation, by selecting our MVC Model and DBContext. It saves the developer time by eliminating the need to write a single line of code for creating CRUD pages. Scaffolding will use Model and our DBContext for generating automatic code for our CRUD operations. We will see in detail in this article how to add Scaffolding in our project for our Student Master CRUD.

Reference 

Prerequisites

  • Visual Studio 2015: You can download it from here.
  • ASP.NET 5 /Core 1.0: Download ASP.NET 5 RC from this link https://get.asp.net/

Using the code

After installing both Visual Studio 2015 and ASP.NET 5, Click Start, then Programs, and select Visual Studio 2015 -- click Visual Studio 2015. Click New, then Project, select Web, and select ASP.NET Web Application. Enter your Project Name and click OK.


Select Web Application under ASP.NET 5 Template and click OK.

 
Create a Database

We will be using our SQL Server database for our CRUD operation. First we create a database named StudentsDB, and a table, StudentMaster. Here is the SQL script to create the database table and a sample record insert query in our table. 

  1. USE MASTER    
  2. GO    
  3.     
  4. -- 1) Check for the Database Exists .If the database is exist then drop and create new DB    
  5. IF EXISTS (SELECT [nameFROM sys.databases WHERE [name] = 'StudentsDB' )    
  6. DROP DATABASE StudentsDB    
  7. GO    
  8.     
  9. CREATE DATABASE StudentsDB    
  10. GO    
  11.     
  12. USE StudentsDB    
  13. GO    
  14.     
  15.     
  16. -- 1) //////////// StudentMasters    
  17.     
  18. IF EXISTS ( SELECT [nameFROM sys.tables WHERE [name] = 'StudentMasters' )    
  19. DROP TABLE StudentMasters    
  20. GO    
  21.     
  22. CREATE TABLE [dbo].[StudentMasters](    
  23.         [StdID] INT IDENTITY PRIMARY KEY,    
  24.         [StdName] [varchar](100) NOT NULL,       
  25.         [Email]  [varchar](100) NOT NULL,       
  26.         [Phone]  [varchar](20) NOT NULL,       
  27.         [Address]  [varchar](200) NOT NULL    
  28. )    
  29.     
  30. -- insert sample data to Student Master table    
  31. INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])    
  32.      VALUES ('Shanu','[email protected]','01030550007','Madurai,India')    
  33.     
  34. INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])    
  35.      VALUES ('Afraz','[email protected]','01030550006','Madurai,India')    
  36.          
  37. INSERT INTO [StudentMasters]   ([StdName],[Email],[Phone],[Address])    
  38.      VALUES ('Afreen','[email protected]','01030550005','Madurai,India')    
  39.          
  40.          
  41.      select * from [StudentMasters]  
 
To change the default connection string with our SQL connection, open the “appsettings.json” file. Yes, this is a JSON file and this file looks like the below image by default.
 
 
Now the default connection string will be something like this:
  1. "ConnectionString": "Server=(localdb)\\mssqllocaldb;Database=aspnet5-MYASP.NET5DemoTest-afb3aac0-d181-4278-8436-cafeeb5a8dbf;Trusted_Connection=True;MultipleActiveResultSets=true"  
Now we change this to our SQL Connection like below,
  1. "ConnectionString":  "Server=YourSQLSERVERNAME;Database=StudentsDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true;"   
Here you can change as per your SQL Connection and save the “appsettings.json” file. The updated JSON file will look like this:
 
 

Creating our Model

We can create a model by adding a new class file in our Model Folder. 

 

Right click the Models folder and click Add New Item. Select Class and enter your class name as “StudentMasters.cs”
 
 
Here our class will look like the below image. Here we will add our model field property.


Add the header file using System.ComponentModel.DataAnnotations; and add all our table field names as property in this model class, as in the following: 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using System.ComponentModel.DataAnnotations;  
  6.   
  7. namespace MYASP.NET5DemoTest.Models  
  8. {  
  9.     public class StudentMasters  
  10.     {  
  11.         [Key]  
  12.         public int StdID { getset; }  
  13.         [Required]  
  14.         [Display(Name = "Name")]  
  15.         public string StdName { getset; }  
  16.         [Required]  
  17.         [Display(Name = "Email")]  
  18.         public string Email { getset; }  
  19.   
  20.         [Required]  
  21.         [Display(Name = "Phone")]  
  22.         public string Phone { getset; }  
  23.   
  24.   
  25.         public string Address { getset; }  
  26.     }  
  27. }  
Now we have created our Model; the next step is to add DBContext for our model.

Creating DbContext

Now we need to create a DBContext for our Entity Framework. Same as with Model Class; add a new class to our Models folder.

Right click the Models folder and click Add New Item. Select Class and enter your class name as “StudentMastersAppContext.cs”

 
Here our class will look like the following screenshot:
 

Now, first we need to add the header file for Entity framework  using Microsoft.Data.Entity;

Next inherit the DbContext to our class, and then create object for our DBContext like the below code. 

  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using System.Threading.Tasks;  
  4. using Microsoft.Data.Entity;  
  5.   
  6. namespace MYASP.NET5DemoTest.Models  
  7. {  
  8.     public class StudentMastersAppContext : DbContext  
  9.     {  
  10.         public DbSet<StudentMasters> Students { getset; }  
  11.     }  
  12. }  
 Now we can create our DB context, and the next step is to add a Service for our Entity Framework.

Adding Entity Framework Service in Startup.cs

Next we need to add our Entity Framework service in Startup.cs. We can find the Startup.cs file from our solution explorer .

Open the Startup.cs file, and we can see by default the ApplicationDBContext will be added in the ConfigureServices method.


Now we can add one more DBContext for our
StudentMastersAppContext asin the below code. 
  1. // Add Entity Framework  
  2.             services.AddEntityFramework()  
  3.                    .AddSqlServer()  
  4.                    .AddDbContext<StudentMastersAppContext>(options =>  
  5.                        options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));  
In ConfigureServices method we add code like this one below. 
  1. public void ConfigureServices(IServiceCollection services)  
  2.         {  
  3.             // Add framework services.  
  4.             services.AddEntityFramework()  
  5.                 .AddSqlServer()  
  6.                 .AddDbContext<ApplicationDbContext>(options =>  
  7.                     options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));  
  8.   
  9.             services.AddIdentity<ApplicationUser, IdentityRole>()  
  10.                 .AddEntityFrameworkStores<ApplicationDbContext>()  
  11.                 .AddDefaultTokenProviders();  
  12.   
  13.             services.AddMvc();  
  14.   
  15.             // Add Entity Framework  
  16.             services.AddEntityFramework()  
  17.                    .AddSqlServer()  
  18.                    .AddDbContext<StudentMastersAppContext>(options =>  
  19.                        options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));  
  20.   
  21.             // Add application services.  
  22.             services.AddTransient<IEmailSender, AuthMessageSender>();  
  23.             services.AddTransient<ISmsSender, AuthMessageSender>();  
  24.         }  
Next step is to add Scaffolding.

Adding Scaffolding:

For adding the Scaffolding Right click Controller folder and click Add -> new Scaffolding Item.

 
 
Select MVC 6 Controller with Views, using Entity Framework and click Add.
 
 
Now we need to select our newly created Model class and our Data Context Class.

Model Class: In Model Class select our Model Class which we created as “StudentMasters”.

Data Context Class: In Data Context select our DBContext class which we created as “StudentMastersAppContext”  

 
Yes, we have completed it now. We can see a new Controller class “StudentMastersController.cs” will be created inside our Controllers folder.

 
We can see this “StudentMastersController.cs” controller class will have auto generated code for our Student Master CRUD operations.
 
 
Inthe Views folder we can see our StudentMasters automatic view will be created for our CRUD operation. Here we have no need to write any code for our CRUD operation. But we can customize this controller and view if required.


Yes, everything is finished now, and we need just run our application and Create/Edit/Delete and View Student Master details.

Add Student Menu:

Before that, we must create a new menu to see our Students page.

For adding a menu click Views Folder -> Open Shared Folder and Open layour.cshtml page.


In layout.cshtml file we can find the following code.
 
  1. <div class="navbar-collapse collapse">  
  2.       <ul class="nav navbar-nav">  
  3.           <li><a asp-controller="Home" asp-action="Index">Home</a></li>  
  4.           <li><a asp-controller="Home" asp-action="About">About</a></li>  
  5.           <li><a asp-controller="Home" asp-action="Contact">Contact</a></li>  
  6.        </ul>  
  7.                     @await Html.PartialAsync("_LoginPartial")  
  8. </div>  
We can remove the About and Contact menu and add our Student menu with the controller name like the following code. 
  1. <div class="navbar-collapse collapse">  
  2.         <ul class="nav navbar-nav">  
  3.              <li><a asp-controller="Home" asp-action="Index">Home</a></li>  
  4.              <li><a asp-controller="StudentMasters" asp-action="Index">Student</a></li>  
  5.         </ul>  
  6.              @await Html.PartialAsync("_LoginPartial")  
  7.    </div>  
Run the Program:

Yes, everything is completed now, and your simple Student CRUD using ASP.NET 5 is completed. Now press F5 and run the project -- you can see the output as in  the following image.

 
Here we will add a new test student details and also we can see the changes updated in SQL Server.
 
 
Read more articles on ASP.NET MVC:

Up Next
    Ebook Download
    View all
    Learn
    View all