Model First Approach in ASP.Net MVC 5

Introduction

As we know there are various approaches for the Entity Framework available with which we can connect with the database from the ASP.NET web application. There are generally three approaches available, given below:

  • Code First Approach
  • Database First Approach
  • Model First Approach

In this article we will work with the Model First Approach using the Entity Framework 6 and using this approach we will connect with the database from the web application. We will create the ASP.NET web application using the MVC Project Template. I am using the Visual Studio 2013 and in this IDE, we use the MVC 5 Project Template to create the web application. I have created an application in which I used the Database First Approach to connect with the database.

Entity Framework 6 Overview

The Entity Framework 6.1 is the latest version of Entity Framework. We will work here in the version 6 of Entity Framework. The following are some features of Entity Framework 6:

  • Async Query and Save
  • Connection Resiliency
  • Code Based Configuration
  • Dependency Resolution
  • Multiple Contexts per Database

You can get the full description of Entity Framework 6 from here.

I am using the Visual Studio 2013 to work with the Entity Framework 6. We can create the application using the Entity Framework 6 that targets .NET 4.0 or .NET 4.5. I am using .NET 4.5.1.

Getting Started

We will now create the MVC 5 application using the Model First Approach. Use the following procedure:

  • Creating Web Application
  • Adding Entity Data Model
  • Working with Entity Data Model Designer
  • Working with Controller and Views
  • do CRUD Operations
  • Working with Database

Creating Web Application

In this section, we will create the ASP.NET web application using the MVC Project Template. Follow the steps given below.

Step 1: Open Visual Studio 2013 and click on New Project.

Step 2: Select the Web tab from the left pane and select the ASP.NET web application and specify the application as "MvcMovie"

Creating Web Application

Step 3: Select the MVC Project Template and click on OK.

Web App using Mvc Project Template

Visual Studio automatically creates the MVC application and adds many files and folders to the project. You can check it out in the Solution Explorer.

Adding Entity Data Model

In this section, we will add the ADO.NET Entity Data Model to the application. We will create the empty model in here. Use the following procedure.

Step 1: In the Solution Explorer, right-click on the Models folder and click on ADO.NET Entity Data Model.

Adding Entity Data Model

Step 2: Specify the model name.

Specifying Model Name

Step 3: In the next Entity Data Model Wizard, select the Empty Model and click on "Finish".

Creating Empty Model in Entity Model Wizard

Now you can see the Entity Data Model Designer.

Entity Data Model Designer

Working with Entity Data Model Designer

In this section, we'll add the entity in the Entity Data Model Designer. We will proceed in this section using following two sections:

  • Adding Entity Model
  • Generate Database from Model

Adding Entity Model

In this section, we'll create the entity model using the following procedure.

Step 1: Right-click on the Data Model Designer and go to add new entity as shown below:

Adding New Entity in Data Model

Step 2: In the next Add Entity wizard, specify the entity name.

Specifying Entity Name

Note: You can change the name of Entity Set that is generated automatically.

Step 3: Now you can see that the entity is created. So, it is time to add a scalar property to the entity. Right-click on the entity and go to add new scalar property.

Adding New Scalar Property

Change the name of the property.

Adding Property Name

Step 4: Add more scalar properties to the entity.

Movie Entity

Generate Database from Model

Now we have generated an entity model. You can also create more entity models in the Data Model Designer. We will now generate the database from the model. Use the following procedure.

Step 1: Right-click on the Data Model Designer surface and select the Generate Database from Model.

Generating Database from Model

Step 2: Now in the Generate Database Wizard, click on New Connection to connect with the database.

Creating New Connection in Database Wizard

Step 3: In the next Connection Properties wizard, specify the server name and the specify the database name.

Specifying Connection Properties

Step 4: Now in the Generate Database Wizard, you can see that the connection is created. Click on the Next button.

Working with Connection in Database Wizard

Step 5: The database summary and script is generated and click on Finish.

Database Summary

Step 6: Now right-click on the script and click on Execute.

Executing Database Script

After executing the database will have been created. You can see your database in the Server Explorer.

Generated Table in Server Explorer

Working with Controller and Views

In this section we will work with the controller and views in MVC 5. So far we have the done the work with the database. We wil now add the MVC 5 controller and view using the Entity Framework. So let's get started with the following procedure.

Step 1: Build the solution at first. When you build the solution then you can find the model class in the Models folder.

Movie DataModel

The Movie class is generated in the models folder. Edit the code with the following highlighted code:

  1. //------------------------------------------------------------------------------  
  2. // <auto-generated>  
  3. //     This code was generated from a template.  
  4. //  
  5. //     Manual changes to this file may cause unexpected behavior in your application.  
  6. //     Manual changes to this file will be overwritten if the code is regenerated.  
  7. // </auto-generated>  
  8. //------------------------------------------------------------------------------  
  9.    
  10. namespace MvcMovie.Models  
  11. {  
  12.     using System;  
  13.     using System.Collections.Generic;  
  14.     using System.ComponentModel.DataAnnotations;  
  15.      
  16.     public partial class Movie  
  17.     {  
  18.         public int Id { getset; }  
  19.         public string Name { getset; }  
  20.         public string Genre { getset; }   
  21.         [Display(Name="Release Date")]  
  22.         [DataType(DataType.Date)]  
  23.         public System.DateTime ReleaseDate { getset; }  
  24.     }  
  25. }  

In the code above, I've added the Data Annotation in which I am changing the display name of the property and date property initialized.

Step 2: In the Solution Explorer, right-click on the Controller and go to Add and then New Scaffolded Item.

Adding New Scaffolded Item

Step 3: In the Add Scaffold wizard, select the MVC 5 Controller using the Entity Framework with Views.

Adding MVC 5 Controller using Entity Framework

Step 4: In the Add Controller Wizard, specify the controller name, select the model class and select the Data Context class and then click Add.

Add Controller Wizard

When you click on Add, the MovieController class is generated in the Controllers folder and the Movie folder is generated in the Views folder. Have a look:

Mvc Project

do CRUD Operations

In this section we will do the CRUD (Create, Read, Update and Delete) operations. So let's start the following procedure.

At first we will create an Action Link to our View. Go to the Views->Shared->_Layout.cshtml file and edit the code with the following highlighted code:

  1. <html>  
  2. <head>  
  3.     <meta charset="utf-8" />  
  4.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  5.     <title>@ViewBag.Title - Movie App</title>  
  6.     @Styles.Render("~/Content/css")  
  7.     @Scripts.Render("~/bundles/modernizr")  
  8.    
  9. </head>  
  10. <body>  
  11.     <div class="navbar navbar-inverse navbar-fixed-top">  
  12.         <div class="container">  
  13.             <div class="navbar-header">  
  14.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  15.                     <span class="icon-bar"></span>  
  16.                     <span class="icon-bar"></span>  
  17.                     <span class="icon-bar"></span>  
  18.                 </button>  
  19.                 @Html.ActionLink("Best Movies""Index""Home", null, new { @class = "navbar-brand" })  
  20.             </div>  
  21.             <div class="navbar-collapse collapse">  
  22.                 <ul class="nav navbar-nav">  
  23.                     <li>@Html.ActionLink("Home""Index""Home")</li>  
  24.                     <li>@Html.ActionLink("About""About""Home")</li>  
  25.                     <li>@Html.ActionLink("Contact""Contact""Home")</li>  
  26.                     <li>@Html.ActionLink("Movies""Index""Movie")</li>  
  27.                 </ul>  
  28.                 @Html.Partial("_LoginPartial")  
  29.             </div>  
  30.         </div>  
  31.     </div>  
  32.     <div class="container body-content">  
  33.         @RenderBody()  
  34.         <hr />  
  35.         <footer>  
  36.             <p>© @DateTime.Now.Year - My Movie Application</p>  
  37.         </footer>  
  38.     </div>  
  39.    
  40.     @Scripts.Render("~/bundles/jquery")  
  41.     @Scripts.Render("~/bundles/bootstrap")  
  42.     @RenderSection("scripts", required: false)  
  43. </body>  
  44. </html>  

In the code above, we have created an action link and edited the app name and title.

Create

In this section, we will do the Create operation.

Step 1: Run the application and in the home page of the application click on Movies.

MVC Home Page

Step 2: In the next window, click on the Create New link to create the record.

Creating New Record

Step 3: Add a record as shown below:

Creating Record using MVC 5

Add a few more records using the same procedure.

Read

Whenever you click on the Movies link, you can read the corresponding records.

Reading Records in MVC 5

Update

We can update the corresponding record using the following procedure.

Step 1: Click on the Edit link in that record.

Editing Records in MVC 5

Step 2: Edit the record and click on the Save button.

Updating Record in MVC 5

Delete

You can delete the record by clicking on the Delete link. Then you can see the windows as in the following:

Deleting Record in MVC 5

Working with Database

The table and records are updated in the database. We can check out this using the Server Explorer. Use the following procedure.

Step 1: Open the Model in the Server Explorer.

Step 2: Expand the Tables folder and right-click on the table and click on the Show Table Data.

Show Table Data

Step 3: The records will display on the screen.

Display Table Record

That's it.

Summary

So far we have applied the Model First Approach of Entity Framework to connect with the database and using the MVC 5 web application we can do the CRUD Operations. Thanks for reading and Happy Coding!!


Similar Articles