Click here to Skip to main content
15,885,985 members
Articles / Web Development / ASP.NET / ASP.NETvNext

CRUD Using Scaffolding And Entity Framework

Rate me:
Please Sign up or sign in to vote.
4.96/5 (16 votes)
1 Mar 2016CPOL4 min read 81.4K   1.8K   31   11
In this article, we will see in detail how to create a simple Student Master CRUD (Create/Read/Update and Delete) using scaffolding.

Introduction

Image 1

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.

Image 2

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

Image 3

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.

SQL
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]

Image 4

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.

Image 5

Now, the default connection string will be something like this:

XML
"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:

XML
"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:

Image 6

Creating Our Model

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

Image 7

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

Image 8

Here, our class will look like the below image. Here, we will add our model field property.

Image 9

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:

C#
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; 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”.

Image 10

Here, our class will look like the following screenshot:

Image 11

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.

C#
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 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.

Image 12

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

Image 13

Now, we can add one more DBContext for our StudentMastersAppContext as in the below code:

C#
// Add Entity Framework
                      services.AddEntityFramework()
                     .AddSqlServer()
                     .AddDbContext<StudentMastersAppContext>(options =>
                       options.UseSqlServer
                       (Configuration["Data:DefaultConnection:ConnectionString"]));

In ConfigureServices method, we add code like this below:

C#
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 Scaffolding Item.

Image 14

Select MVC 6 Controller with Views, using Entity Framework and click Add.

Image 15

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”.

Image 16

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

Image 17

We can see this “StudentMastersController.cs” controller class will have auto generated code for our Student Master CRUD operations.

Image 18

In the 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.

Image 19

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 layout.cshtml page.

Image 20

In layout.cshtml file, we can find the following code:

HTML
<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 the controller name like the following code:

HTML
<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 as in the following image:

Image 21

Here, we will add a new test student details and also we can see the changes updated in SQL Server.

Image 22

History

  • 2016/03/01: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

Comments and Discussions

 
QuestionThis is not a ASP.NET Core Project Pin
marcoex99926-Aug-16 6:58
marcoex99926-Aug-16 6:58 
AnswerRe: This is not a ASP.NET Core Project Pin
syed shanu26-Aug-16 13:34
mvasyed shanu26-Aug-16 13:34 
GeneralRe: This is not a ASP.NET Core Project Pin
marcoex99931-Aug-16 4:04
marcoex99931-Aug-16 4:04 
QuestionRelated Entities Pin
Matteo Pozzani22-Mar-16 0:20
Matteo Pozzani22-Mar-16 0:20 
QuestionFew questions about your post and ASP.Net Core Pin
Tridip Bhattacharjee8-Mar-16 20:05
professionalTridip Bhattacharjee8-Mar-16 20:05 
AnswerRe: Few questions about your post and ASP.Net Core Pin
syed shanu8-Mar-16 20:16
mvasyed shanu8-Mar-16 20:16 
GeneralRe: Few questions about your post and ASP.Net Core Pin
Tridip Bhattacharjee9-Mar-16 20:52
professionalTridip Bhattacharjee9-Mar-16 20:52 
QuestionGreat article. Pin
Kyle GTwo4-Mar-16 1:53
Kyle GTwo4-Mar-16 1:53 
AnswerRe: Great article. Pin
Member 1116243529-Mar-16 22:18
Member 1116243529-Mar-16 22:18 
GeneralMy vote of 5 Pin
Adroittech3-Mar-16 23:03
professionalAdroittech3-Mar-16 23:03 
GeneralMy vote of 5 Pin
Santhakumar M1-Mar-16 4:07
professionalSanthakumar M1-Mar-16 4:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.