Building Web Application Using Entity Framework And MVC 5: Part One

This article explains the following:

  • Creating a database in Microsoft SQL Server
  • Brief overview of ASP.NET MVC
  • Implementing Entity Framework Database-First approach
  • Creating a simple Signup page

Before you go any further ensure that you have basic knowledge of the following technologies:

  • SQL Server
  • Visual Studio
  • ASP.NET MVC and how stuff works in MVC
  • Entity Framework
  • C#
  • Basics of HTML, CSS and JavaScript/jQuery

This article will guide you through the basic procedure of how to create a simple web application using ASP.NET MVC 5 with a real-world example using Entity Framework Database-First approach. I'll try to keep this demo as simple as possible so beginners can easily follow. You can skip STEP 1 if you already have an existing database. Here's the list of the series for this application:

ASP.NET MVC Overview

Before we start building an MVC application let's talk a bit about MVC because it is very important to understand how the MVC framework works.


ASP.NET MVC gives you a powerful, pattern-based way to build dynamic websites that enable a clean separation of concerns and that gives you full control over mark-up for enjoyable and agile development.

To make it more clear, here's how I view the high-level process of MVC:

Unlike ASP.NET WebForms in which a request is going directly to a page file (.ASPX), in MVC, when a user requests a page, it will first talk to the Controller, process data when necessary and return ViewModels to the View for the user to see.


Model objects are the parts of the application that implement the logic for the application domain data. Often, model objects retrieve and store model state in a database.


Controllers are the components that handle user interaction, work with the model and ultimately select a view to render in the browser.


Views are the components that display the application's User Interface (UI), typically this UI is created from the model data.

STEP 1: Creating a Database

Open SQL Server or SQL Server Express Management Studio and then create a database by doing the following:

  • Right-click on the Databases folder
  • Select New Database
  • Enter a database name and then click OK. Note that in this demo I used “DemoDB” as my database name.

The “DemoDB” database should be created like in the image below:

Note that you can also write a SQL script to create a database.

Now open a New Query window or just press CTRL + N to launch the query window and then run the following scripts:

LOOKUPRole table

  1. USE [DemoDB]  
  2. GO  
  4. CREATE TABLE [dbo].[LOOKUPRole](  
  5.     [LOOKUPRoleID] [int] IDENTITY(1,1) NOT NULL,  
  6.     [RoleName] [varchar](100) DEFAULT '',  
  7.     [RoleDescription] [varchar](500) DEFAULT '',  
  8.     [RowCreatedSYSUserID] [intNOT NULL,  
  9.     [RowCreatedDateTime] [datetime]  DEFAULT GETDATE(),  
  10.     [RowModifiedSYSUserID] [intNOT NULL,  
  11.     [RowModifiedDateTime] [datetime] DEFAULT GETDATE(),  
  13.     )  
  14. GO  

Adding sample data to LOOKUPRole

  1. INSERT INTO LOOKUPRole (RoleName,RoleDescription,RowCreatedSYSUserID,RowModifiedSYSUserID)  
  2.        VALUES ('Admin','Can Edit, Update, Delete',1,1)  
  3. INSERT INTO LOOKUPRole (RoleName,RoleDescription,RowCreatedSYSUserID,RowModifiedSYSUserID)  
  4.        VALUES ('Member','Read only',1,1)  
SYSUser table
  1. USE [DemoDB]  
  2. GO  
  4. CREATE TABLE [dbo].[SYSUser](  
  5.     [SYSUserID] [int] IDENTITY(1,1) NOT NULL,  
  6.     [LoginName] [varchar](50) NOT NULL,  
  7.     [PasswordEncryptedText] [varchar](200) NOT NULL,  
  8.     [RowCreatedSYSUserID] [intNOT NULL,  
  9.     [RowCreatedDateTime] [datetime] DEFAULT GETDATE(),  
  10.     [RowModifiedSYSUserID] [intNOT NULL,  
  11.     [RowMOdifiedDateTime] [datetime] DEFAULT GETDATE(),  
  12.     PRIMARY KEY (SYSUserID)  
  13. )  
  15. GO  

SYSUserProfile table

  1. USE [DemoDB]  
  2. GO  
  5. CREATE TABLE [dbo].[SYSUserProfile](  
  6.     [SYSUserProfileID] [int] IDENTITY(1,1) NOT NULL,  
  7.     [SYSUserID] [intNOT NULL,  
  8.     [FirstName] [varchar](50) NOT NULL,  
  9.     [LastName] [varchar](50) NOT NULL,  
  10.     [Gender] [char](1) NOT NULL,  
  11.     [RowCreatedSYSUserID] [intNOT NULL,  
  12.     [RowCreatedDateTime] [datetime] DEFAULT GETDATE(),  
  13.     [RowModifiedSYSUserID] [intNOT NULL,  
  14.     [RowModifiedDateTime] [datetime] DEFAULT GETDATE(),  
  15.     PRIMARY KEY (SYSUserProfileID)  
  16.     )  
  17. GO  
  20. REFERENCES [dbo].[SYSUser] ([SYSUserID])  
  21. GO  

SYSUserRole table

  1. USE [DemoDB]  
  2. GO  
  4. CREATE TABLE [dbo].[SYSUserRole](  
  5.     [SYSUserRoleID] [int] IDENTITY(1,1) NOT NULL,  
  6.     [SYSUserID] [intNOT NULL,  
  7.     [LOOKUPRoleID] [intNOT NULL,  
  8.     [IsActive] [bitDEFAULT (1),  
  9.     [RowCreatedSYSUserID] [intNOT NULL,  
  10.     [RowCreatedDateTime] [datetime] DEFAULT GETDATE(),  
  11.     [RowModifiedSYSUserID] [intNOT NULL,  
  12.     [RowModifiedDateTime] [datetime] DEFAULT GETDATE(),  
  13.     PRIMARY KEY (SYSUserRoleID)  
  14. )  
  15. GO  
  18. REFERENCES [dbo].[LOOKUPRole] ([LOOKUPRoleID])  
  19. GO  
  22. REFERENCES [dbo].[SYSUser] ([SYSUserID])  
  23. GO  

That's it. We just created 4 database tables. The next step is to create the web application.

STEP 2: Adding a new ASP.NET MVC 5 Project

Let's go ahead and fire up Visual Studio 2015 and select File > New > Project. In the New Project dialog select Templates > Visual C# > ASP.NET Web Application. See the image below for a clear view:

Name your project whatever you like and then click OK. Note that for this demo I named the project “MVC5RealWorld”. Now after that you should be able to see the “New ASP.NET Project” dialog. See the image below:

The New ASP.NET Project dialog for ASP.NET 4.6 templates allow you to select what type of project you want to create, configure any combination of technologies such as WebForms, MVC or Web API, configure unit test project, configure authentication option and also offers a new option to host your website in the Azure cloud. Adding to that, it also provide templates for ASP.NET 5.

In this article I will only be covering the creation of an MVC 5 application. So the details of each configuration like unit testing, authentication, hosting in cloud and so on will not be covered.

Now select Empty under ASP.NET 4.6 templates and then check the MVC option under folders and core reference as shown from the image above. The reason for this is that we will create an empty MVC application from scratch. Click OK to let Visual Studio generate the necessary files and templates needed for you to run MVC.

You should be able to see something as in the following:

STEP 3: Setting up the Data Access

For this example, I'm going to use Database-First with Entity Framework 6 (EF) as our data access mechanism so that we can just program against the conceptual application model instead of programming directly against our database.

As a quick recap, a Model is just a class. Yes it's a class that implements the logic for your application's domain data. Often, model objects retrieved and store model state in database.

Now let's setup our Model folder structure by adding the following sub-folders under the Models folder:

  • DB
  • EntityManager
  • ViewModel

Our model structure should look something as in the following:

The DB folder is where we store our entity model (EDMX). To add an entity, right-click on the DB folder and select Add > New Item > Data > ADO.NET Entity Data Model. See the image below for a clear view:

You can name your entity model as you would like but for this example I just named it “DemoModel” for simplicity. Now click Add to continue and on the next step select “EF Designer from Database” since we will use the database first approach to work with existing database. Click Next to proceed. In the next step click on the “New Connection” button and then select “Microsoft SQL Server (SqlClient)” as the data source then click Next. You should see this dialog below:

Supply the SQL Server name and select the database that we have just created in STEP 1. If you have an existing database, then use that instead. Also note that I am using Windows Authentication for logging into my SQL Server. Once you've done supplying the necessary field then click on “Test Connection” to verify the connectivity. If it is successful then just click OK.

You should now see the following dialog:

Notice that the connection string was automatically generated for you. Click Next and then select Entity Framework 6.x to bring up this dialog below:

Now select the table(s) that you want to use in your application. For this example I selected all the tables because we will use those in our application. Clicking the Finish button will generate the Entity Model for you as shown in the image below:

What happened there is that EF automatically generates the business objects for you and lets you query against it. The EDMX or the entity data model will serve as the main gateway by which you retrieve objects from the database and resubmit changes.

STEP 4: Creating the Signup Page

Adding ViewModels

Just to recap, Entity Framework will generate the business model objects and manage Data Access within the application. As a result, the classes LOOKUPRole, SYSUserRole, SYSUser and SYSUserProfile are automatically created by EF and it features all the fields from the database table as properties of the class.

I don't want to use these classes directly in the View so I decided to create a separate class that just holds the properties I needed in the View. Now let's add the “UserModel” class by right-clicking on the "ViewModel" folder then select Add > Class. The "UserModel.cs" file is where we put all user-related model views. For the Signup page we will add the “UserSignUpView” class. So in the UserModel file add the following class:

  1. using System.ComponentModel.DataAnnotations;  
  2. namespace MVC5RealWorld.Models.ViewModel  
  3. {  
  4.     public class UserSignUpView  
  5.     {   [Key]
  6.         public int SYSUserID { getset; }  
  7.         public int LOOKUPRoleID { getset; }  
  8.         public string RoleName { getset; }  
  9.         [Required(ErrorMessage = "*")]  
  10.         [Display(Name = "Login ID")]  
  11.         public string LoginName { getset; }  
  12.         [Required(ErrorMessage = "*")]  
  13.         [Display(Name = "Password")]  
  14.         public string Password { getset; }  
  15.         [Required(ErrorMessage = "*")]  
  16.         [Display(Name = "First Name")]  
  17.         public string FirstName { getset; }  
  18.         [Required(ErrorMessage = "*")]  
  19.         [Display(Name = "Last Name")]  
  20.         public string LastName { getset; }  
  21.         public string Gender { getset; }  
  22.     }  
  23. }  

Notice that I added the Required and DisplayName attributes for each property in the UserSignUpView class. These attributes are called Data Annotations. Data annotations are attribute classes that live under the System.ComponentModel.DataAnnotations namespace that you can use to decorate classes or properties to enforce pre-defined validation rules.

I'll use this validation technique because I want to keep a clear separation of concerns using the MVC pattern and couple that with data annotations in the model, then your validation code becomes much simpler to write, maintain and test.

For more information about Data Annotations refer to Data Annotations. And of course you can find more examples about it by doing a simple search at Google or Bing.

Adding the UserManager Class

The next step that we will do is to create the “UserManger” class that would handle the CRUD operations (Create, Read, Update and Delete operations) of a certain table. The purpose of this class is to separate the actual data operations from our controller and to have a central class for handling insert, update, fetch and delete operations.


Please keep in mind that in this step I'm only doing the insert part in which a user can add new data from the View to the database. I'll talk about how to do update, fetch and delete with MVC in my next article. So this time we'll just focus on the insertion part first.

Since this demo is intended to make a web app as simple as possible I will not be using TransactionScope and Repository pattern. In a real complex web app you may want to consider using TransactionScope and Repository for your Data Access.

Now right-click on the "EntityManager" folder and then add a new class by selecting Add > Class and name the class "UserManager". Here's the code block for the "UserManager.cs" class:

  1. using System;  
  2. using System.Linq;  
  3. using MVC5RealWorld.Models.DB;  
  4. using MVC5RealWorld.Models.ViewModel;  
  6. namespace MVC5RealWorld.Models.EntityManager  
  7. {  
  8.     public class UserManager  
  9.     {  
  10.         public void AddUserAccount(UserSignUpView user) {  
  12.             using (DemoDBEntities db = new DemoDBEntities()) {  
  14.                 SYSUser SU = new SYSUser();  
  15.                 SU.LoginName = user.LoginName;  
  16.                 SU.PasswordEncryptedText = user.Password;  
  17.                 SU.RowCreatedSYSUserID = user.SYSUserID > 0 ? user.SYSUserID : 1;  
  18.                 SU.RowModifiedSYSUserID = user.SYSUserID > 0 ? user.SYSUserID : 1; ;  
  19.                 SU.RowCreatedDateTime = DateTime.Now;  
  20.                 SU.RowMOdifiedDateTime = DateTime.Now;  
  22.                 db.SYSUsers.Add(SU);  
  23.                 db.SaveChanges();  
  25.                 SYSUserProfile SUP = new SYSUserProfile();  
  26.                 SUP.SYSUserID = SU.SYSUserID;  
  27.                 SUP.FirstName = user.FirstName;  
  28.                 SUP.LastName = user.LastName;  
  29.                 SUP.Gender = user.Gender;  
  30.                 SUP.RowCreatedSYSUserID = user.SYSUserID > 0 ? user.SYSUserID : 1;  
  31.                 SUP.RowModifiedSYSUserID = user.SYSUserID > 0 ? user.SYSUserID : 1;  
  32.                 SUP.RowCreatedDateTime = DateTime.Now;  
  33.                 SUP.RowModifiedDateTime = DateTime.Now;  
  35.                 db.SYSUserProfiles.Add(SUP);  
  36.                 db.SaveChanges();  
  39.                 if (user.LOOKUPRoleID > 0) {  
  40.                     SYSUserRole SUR = new SYSUserRole();  
  41.                     SUR.LOOKUPRoleID = user.LOOKUPRoleID;  
  42.                     SUR.SYSUserID = user.SYSUserID;  
  43.                     SUR.IsActive = true;  
  44.                     SUR.RowCreatedSYSUserID = user.SYSUserID > 0 ? user.SYSUserID : 1;  
  45.                     SUR.RowModifiedSYSUserID = user.SYSUserID > 0 ? user.SYSUserID : 1;  
  46.                     SUR.RowCreatedDateTime = DateTime.Now;  
  47.                     SUR.RowModifiedDateTime = DateTime.Now;  
  49.                     db.SYSUserRoles.Add(SUR);  
  50.                     db.SaveChanges();  
  51.                 }  
  52.             }  
  53.         }  
  55.         public bool IsLoginNameExist(string loginName) {  
  56.             using (DemoDBEntities db = new DemoDBEntities()) {  
  57.                 return db.SYSUsers.Where(o => o.LoginName.Equals(loginName)).Any();  
  58.             }  
  59.         }  
  60.     }  
  61. }  

The AddUserAccount() is a method that inserts data to the database using Entity Framework. The IsLoginNameExist() is a method that returns boolean. It checks the database for an existing data using LINQ syntax.

Adding the Controllers

Since our model was already set, let's go ahead and add the "AccountController". To do this, just right-click on the "Controllers" folder and select Add > Controller > MVC 5 Controller - Empty and then click Add. In the next dialog name the controller "AccountController" and then click Add to generate the class.

Now here's the code block for "AccountController":

  1. using System.Web.Mvc;  
  2. using System.Web.Security;  
  3. using MVC5RealWorld.Models.ViewModel;  
  4. using MVC5RealWorld.Models.EntityManager;  
  6. namespace MVC5RealWorld.Controllers  
  7. {  
  8.     public class AccountController : Controller  
  9.     {        
  10.         public ActionResult SignUp() {  
  11.             return View();  
  12.         }  
  14.         [HttpPost]  
  15.         public ActionResult SignUp(UserSignUpView USV) {  
  16.             if (ModelState.IsValid) {  
  17.                 UserManager UM = new UserManager();  
  18.                 if (!UM.IsLoginNameExist(USV.LoginName)) {  
  19.                     UM.AddUserAccount(USV);  
  20.                     FormsAuthentication.SetAuthCookie(USV.FirstName, false);  
  21.                     return RedirectToAction("Welcome""Home");  
  23.                 }  
  24.                 else  
  25.                     ModelState.AddModelError("""Login Name already taken.");  
  26.             }  
  27.             return View();  
  28.         }  
  29.     }  
  30. }  

The AccountController has two main methods. The first one is the "SignUp" that returns the "SignUp.cshtml" View. The second one is also named "SignUp" but it is decorated with the "[HttpPost]" attribute. This attribute specifies that the overload of the "SignUp" method can be invoked only for POST requests.

The second method is responsible for inserting a new entry into the database and automatically authenticate the users using the FormsAuthentication.SetAuthCookie() method. This method creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response or to the URL if you are using cookieless authentication. After authenticating, we then redirect the users to the Welcome.cshtml page.

Now add another Controller and name it "HomeController". This controller would be our controller for our default page. We will create the "Index" and the "Welcome" Views for this controller in the next step. Here's the code for the "HomeController" class:

  1. using System.Web.Mvc;  
  2. namespace MVC5RealWorld.Controllers  
  3. {  
  4.     public class HomeController : Controller  
  5.     {  
  6.         public ActionResult Index() {  
  7.             return View();  
  8.         }  
  10.         [Authorize]  
  11.         public ActionResult Welcome() {  
  12.             return View();  
  13.         }  
  15.     }  
  16. }  

The HomeController class consists of two ActionResult methods, such as Index and Welcome. The "Index" method serves as our default redirect page and the "Welcome" method will be the page where we redirect the users after they have successfully registered. We have also decorated it with the "[Authorize]" attribute so that this method will only be available for the logged-in users.

To configure a default page you can go to App_Start > RouteConfig. From there you should be able to see something like this:

  1. public static void RegisterRoutes(RouteCollection routes)  
  2. {  
  3.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  5.             routes.MapRoute(  
  6.                 name: "Default",  
  7.                 url: "{controller}/{action}/{id}",  
  8.                 defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
  9.             );  
  10. }  

Adding the Views

There are two possible ways to add Views. You can either manually create the Views folder yourself and add the corresponding .CSHTML files or by right-clicking on the Controller's action method just like in the image shown below:

Clicking Add View will show this dialog below:

Just click Add since we don't need to do anything with the Index page for this demo. Now modify the Index page and replace it with the following HTML markup:


  1. @{  
  2.     ViewBag.Title = "Index";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  6. <h2>Index</h2>  
  7. <br/>  
  8. No Account yet? @Html.ActionLink("Signup Now!", "SignUp", "Account")  

The ActionLink in the markup above allows you to navigate to the SignUp page that lives under the Account controller. Now add a View to the Welcome action by doing the same as we did by adding the Index page. Here's the Welcome page HTML markup:


  1. @{  
  2.     ViewBag.Title = "Welcome";  
  3.     Layout = "~/Views/Shared/_Layout.cshtml";  
  4. }  
  6. <h2>Hi <b>@Context.User.Identity.Name</b>! Welcome to my first MVC 5 Web App!</h2>  


Now switch back to AccountController and add a View for the SignUp page. In the Add View dialog select “Create” as the scaffold template, select the UserSignUpView as the model and the DemoDBEntities as the data context as shown in the image below:

Click Add to let Visual Studio scaffolds the UI for you. The term “Scaffolding” allows you to quickly generate the UI that you can edit and customize.

Now we need to trim down the generated fields because there are some fields that we don't actually need users to see like the RoleName and IDs. Adding to that I also modified the Password to use the PasswordFor HTML helper and use DropDownListFor for displaying the Gender. Here's the trimmed down HTML markup for the SignUp page: 

  1. @model MVC5RealWorld.Models.ViewModel.UserSignUpView  
  3. @{  
  4.     ViewBag.Title = "SignUp";  
  5.     Layout = "~/Views/Shared/_Layout.cshtml";  
  6. }  
  8. <h2>SignUp</h2>  
  10. @using (Html.BeginForm())   
  11. {  
  12.     @Html.AntiForgeryToken()  
  14.     <div class="form-horizontal">  
  15.         <hr />  
  16.         @Html.ValidationSummary(true, "", new { @class = "text-danger" })  
  17.         <div class="form-group">  
  18.             @Html.LabelFor(model => model.LoginName, htmlAttributes: new { @class = "control-label col-md-2" })  
  19.             <div class="col-md-10">  
  20.                 @Html.EditorFor(model => model.LoginName, new { htmlAttributes = new { @class = "form-control" } })  
  21.                 @Html.ValidationMessageFor(model => model.LoginName, "", new { @class = "text-danger" })  
  22.             </div>  
  23.         </div>  
  25.         <div class="form-group">  
  26.             @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
  27.             <div class="col-md-10">  
  28.                 @Html.PasswordFor(model => model.Password, new  { @class = "form-control" } )  
  29.                 @Html.ValidationMessageFor(model => model.Password, "", new { @class = "text-danger" })  
  30.             </div>  
  31.         </div>  
  33.         <div class="form-group">  
  34.             @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })  
  35.             <div class="col-md-10">  
  36.                 @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })  
  37.                 @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })  
  38.             </div>  
  39.         </div>  
  41.         <div class="form-group">  
  42.             @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })  
  43.             <div class="col-md-10">  
  44.                 @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })  
  45.                 @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })  
  46.             </div>  
  47.         </div>  
  49.         <div class="form-group">  
  50.             @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })  
  51.             <div class="col-md-10">  
  52.                 @Html.DropDownListFor(model => model.Gender, new List<SelectListItem> {  
  53.                     new SelectListItem { Text="Male"Value="M" },  
  54.                     new SelectListItem { Text="Female"Value="F" }  
  55.                 }, new { @class = "form-control" })  
  56.             </div>  
  57.         </div>  
  59.         <div class="form-group">  
  60.             <div class="col-md-offset-2 col-md-10">  
  61.                 <input type="submit" value="Register" class="btn btn-default" />  
  62.             </div>  
  63.         </div>  
  64.     </div>  
  65. }  
  67. <div>  
  68.     @Html.ActionLink("Back to Main", "Index","Home")  
  69. </div>  

The markup above is a strongly-type view. This strongly typed approach enables better compile-time checking of your code and richer IntelliSense in the Visual Studio editor. By including a @model statement at the top of the view template file, you can specify the type of object that the view expects. In this case it uses the MVC5RealWorld.Models.ViewModel.UserSignUpView.

If you also noticed, after adding the views, Visual Studio automatically structures the folders for your Views. See the image below:

STEP 5: Running the application

The following are the outputs from running the page in the browser.

On initial load

Page validation triggers

Supplying the required fields

After successful registration

That's it! I hope you will find this article useful. J

In my next article I'll cover how to create a Login page so stay tuned.

Similar Articles