ASP.NET 5 CRUD using Scaffolding and Entity Framework
https://msdnshared.blob.core.windows.net/media/2016/05/0640_NinjaAwardTinyGold.pngGold Award Winner
You can download the Source Code from this link Download Source Code
Introduction
https://gallery.technet.microsoft.com/site/view/file/148157/1/1.gif
In this article we will see in detail of how to create a simple Students Master CRUD (Create/Read/Update and Delete) using ASP.NET 5 now it’s ASP.NET Core 1.0 by using scaffolding.
Both ASP.NET 5 and ASP.NET Core 1.0 are the same. Now ASP.NET 5 is called as ASP.NET Core 1.0 so in this article here after we will be using ASP.NET Core 1.0.
What is Scaffolding:
Now CRUD is very easy and simple by using Scaffolding. Yes Scaffolding will automatically generate code on Controller and view for performing our CRUD operation by selecting our MVC Model and DBContext. It saves developer time by no 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 of how to add Scaffolding in our project for our Student master CRUD.** **
Reference link
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 installed both Visual Studio 2015 and ASP.NET 5 RC, 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.
https://gallery.technet.microsoft.com/site/view/file/148158/1/1.PNG
Select Web Application under ASP.NET 5 Template and click OK.
https://gallery.technet.microsoft.com/site/view/file/148160/1/2.PNG
Create a Database
We will be using our SQL Server database for our CRUD operation. First we create a database named as StudentsDB and a table as StudentMaster. Here is the SQL script to create Database table and sample record insert query in our table.
USE MASTER
GO
-- 1) Check for the Database Exists .If the database is exist then drop and create new DB
IF EXISTS (SELECT [name] FROM sys.databases WHERE [name] = 'StudentsDB' )
DROP DATABASE StudentsDB
GO
CREATE DATABASE StudentsDB
GO
USE StudentsDB
GO
-- 1) //////////// StudentMasters
IF EXISTS ( SELECT [name] FROM sys.tables WHERE [name] = 'StudentMasters' )
DROP TABLE StudentMasters
GO
CREATE TABLE [dbo].[StudentMasters](
[StdID] INT IDENTITY PRIMARY KEY,
[StdName] [varchar](100) NOT NULL,
[Email] [varchar](100) NOT NULL,
[Phone] [varchar](20) NOT NULL,
[Address] [varchar](200) NOT NULL
)
-- insert sample data to Student Master table
INSERT INTO [StudentMasters] ([StdName],[Email],[Phone],[Address])
VALUES ('Shanu','syedshanumcain@gmail.com','01030550007','Madurai,India')
INSERT INTO [StudentMasters] ([StdName],[Email],[Phone],[Address])
VALUES ('Afraz','Afraz@afrazmail.com','01030550006','Madurai,India')
INSERT INTO [StudentMasters] ([StdName],[Email],[Phone],[Address])
VALUES ('Afreen','Afreen@afreenmail.com','01030550005','Madurai,India')
select * from [StudentMasters]
Database Connection String:
Now we need to change the local connection string from ASP.Net 5 project with our SQL Server connection.
**Note: **In ASP.NET 5 we need to use “appsettings.json” file instead of web.config. Yes in ASP.NET 5 there is no web.config file for connection string we need use the “appsettings.json”. We can find the “appsettings.json” file from our ASP.NET 5 solution.
https://gallery.technet.microsoft.com/site/view/file/148162/1/3.PNG
To change the default connection string with our SQL connection open the “appsettings.json” file .Yes this is JSON file and this file looks like below Image by default.
https://gallery.technet.microsoft.com/site/view/file/148164/1/4.PNG
Now the default connection string will be something like this:
"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:
"ConnectionString": "Server=YourSQLSERVERNAME;Database=StudentsDB;user id=SQLID;password=;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 be looks like this.
https://gallery.technet.microsoft.com/site/view/file/148165/1/5.PNG
Creating our Model
We can create a model by adding a new class file in our Model Folder.
https://gallery.technet.microsoft.com/site/view/file/148166/1/6.PNG
Right click the Models folder and click Add New Item .Select Class and enter your class name as “StudentMasters.cs”
https://gallery.technet.microsoft.com/site/view/file/148167/1/7.PNG
Here our class will be look like below image. Here we will add our model field property.
https://gallery.technet.microsoft.com/site/view/file/148170/1/8.PNG
Add the header file using System.ComponentModel.DataAnnotations; and add all our table field name as property in this model class like below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace MYASP.NET5DemoTest.Models
{
public class StudentMasters
{
[Key]
public int StdID { get; set; }
[Required]
[Display(Name = "Name")]
public string StdName { get; set; }
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[Display(Name = "Phone")]
public string Phone { get; set; }
public string Address { get; set; }
}
}
Now we have created our Model next step is to add DBContext for our model.
Creating DbContext
Now we need to create a DBContext for our Entity Framework. Same like 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”
https://gallery.technet.microsoft.com/site/view/file/148171/1/9.PNG
Here our class will look like below image.
https://gallery.technet.microsoft.com/site/view/file/148172/1/10.PNG
Now first we need to add the header file for Entity Framework as using Microsoft.Data.Entity. Next inherit the DbContext to our class and then create object for our DBContext like below code.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Data.Entity;
namespace MYASP.NET5DemoTest.Models
{
public class StudentMastersAppContext : DbContext
{
public DbSet<StudentMasters> Students { get; set; }
}
}
Now we can created our DB context and 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.
https://gallery.technet.microsoft.com/site/view/file/148173/1/11.PNG
Open the Startup.cs file and we can see by default the ApplicationDBContext will be added in ConfigureServices method.
https://gallery.technet.microsoft.com/site/view/file/148174/1/12.PNG
Now we can add one more DB Context for our StudentMastersAppContext like below code.
// Add Entity Framework
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<StudentMastersAppContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
In ConfigureServices method we add like this code below.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc();
// Add Entity Framework
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<StudentMastersAppContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
// Add application services.
services.AddTransient<IEmailSender, AuthMessageSender>();
services.AddTransient<ISmsSender, AuthMessageSender>();
}
Next step is to add Scaffolding.
Adding Scaffolding:
For adding the Scaffolding right click Controller folder and click Add -> New Scaffolded Item.
https://gallery.technet.microsoft.com/site/view/file/148176/1/13.PNG
Select MVC 6 Controller with Views, using Entity Framework and click Add.
https://gallery.technet.microsoft.com/site/view/file/148177/1/14.PNG
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”
https://gallery.technet.microsoft.com/site/view/file/148179/1/2.gif
Yes we have completed now. We can see a new Controller class “StudentMastersController.cs” will be created inside our Controllers folder.
https://gallery.technet.microsoft.com/site/view/file/148180/1/16.PNG
We can see this “StudentMastersController.cs” controller class will have auto generated code for our Student Master CRUD operations.
https://gallery.technet.microsoft.com/site/view/file/148181/1/17.PNG
In views folder we can see for our StudentMasters automatic view will be created for our CRUD operation. Here we no need to write any code for our CRUD operation. But we can customize this controller and view if required.
https://gallery.technet.microsoft.com/site/view/file/148182/1/18.PNG
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 create a new menu to see our Students page.
For adding a menu click Views Folder -> Open Shared Folder and Open layout.cshtml page.
https://gallery.technet.microsoft.com/site/view/file/148183/1/19.PNG
In layout.cshtml file we can find the below code.
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-controller="Home" asp-action="About">About</a></li>
<li><a asp-controller="Home" asp-action="Contact">Contact</a></li>
</ul>
@await Html.PartialAsync("_LoginPartial")
</div>
We can remove the About and Contact menu and add our Student menu with controller name like below code.
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li><a asp-controller="Home" asp-action="Index">Home</a></li>
<li><a asp-controller="StudentMasters" asp-action="Index">Student</a></li>
</ul>
@await Html.PartialAsync("_LoginPartial")
</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 like this below image.
https://gallery.technet.microsoft.com/site/view/file/148184/1/3.gif
Here we will add a new test student details and also we can see the changes updated in SQL Server.
https://gallery.technet.microsoft.com/site/view/file/148185/1/4.gif
You can download the Source Code from this link Download Source Code