Understanding ASP.NET MVC5 Model First Approach with EF6

By | January 18, 2015
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest

As a scalable framework for building high-end web applications, ASP.NET MVC5 would have definitely helped you in boosting your interest in handling web app development.

Considering your urge for learning more about the absolutely stunning world of ASP.NET MVC Development, I’ve written this tutorial which focuses on using the model first approach for connecting the ASP.NET app with database.

If you are preparing for an interview, you can follow here for detailed list of Entity Framework Interview Questions.

As you read through this post, you’ll come to know more about the Model First approach used in ASP.NET MVC5, its advantages along with a simple example that will enable you to understand its use during ASP.NET development.

You are developing an ASP.NET MVC news aggregation application that will be deployed to servers on multiple networks. The application must be compatible with multiple browsers. A user can search the website for news articles. You must track the page number that the user is viewing in search results. You need to program the location for storing state information about the user’s search. What should you do?

  • A. Store search results and page index in Session.
  • B. Use Application state to store search terms and page index.
  • C. Use QueryString to store search terms and page index.
  • D. Store search results and page index in TempData.
  • For a complete MVC Online Test and MCSD Practice Exams including 70-486 (Developing ASP.NET MVC Web Applications) , Click Here.
  • If you are interested to improve your skill on ASP.NET MVC, Entity Framework and AngularJS by taking a complete training course, follow here.
  • Looking for MVC Developer’s Job? Latest MVC Developer’s Jobs at the end of this article.

 Correct Answer: C

To start off, let’s take a closer look at the Model First approach for connecting app with database

Before proceeding ahead with the explanation of steps involved in usage of model first technique, I’d like you to know more about the same. Well, the Model First approach has been introduced, keeping the designers in mind. That means, this process of connecting app with database works as the best match for designers who’re very keen of writing lengthy code or SQL commands. The in-built wizards do everything for you, ranging from creation of application and addition of entity data model to generation of database from model and performing the CRUD(Create, Read, Update and Delete) operations.Model First Development

  • Learn ASP NET MVC 5 step by step [Maruti Makwana, Corporate Trainer] 28 Lectures, 2.5 Hours Video, Intermediate Level
    Very easy to learn video series on Asp.Net MVC 5 Specially for those who are familiar with Asp.Net Web forms.
  • AngularJS for ASP.NET MVC Developers [Brett Romero] 10 Lectures, 1 hour video, Intermediate Level
    The Fastest Way For .NET Developers To Add AngularJS To Their Resume
  • ASP.NET with Entity Framework from Scratch [Manzoor Ahmad, MCPD | MCT] 77 Lectures, 10 hour video, All Level
    Latest approach of web application development
  • Comprehensive ASP.NET MVC [3D BUZZ] 34 lectures, 14 Hours Video, All Levels
    From zero knowledge of ASP.NET to deploying a complete project to production.

You can follow for a complete list of related Web and Mobile Development Online Courses.

Now, let me list out a few commendable advantages of using the Model First approach in ASP.NET MVC5

  • Works best for small easy app development projects
    With Model first approach, you just need to draw your model and the workflow will automatically generate the database script with the template being used for adding entities and their related properties. This is something that will serve as a handy option during execution of simple and less complex projects.
  • Eliminates the need for recreating database each time an entity or its property needs to be updated
    Since its your model that defines the database, you can easily do away with the need for recreating the database each time an entity or any of its properties need to be altered. All you need to do is simply update the database scheme or you may even opt for updating the database project in Visual Studio.

And finally, let me teach you the implementation of model first approach using the Entity Framework 6 for connecting with the database via the web app

In this example, I’ll be using the MVC5 Project Template for creating ASP.NET web application along with Visual Studio 2013 as the chosen IDE(Integrated Development Environment).

Now, the steps for connecting ASP.NET application with database using the ‘Model First’ technique:

  1. Create the ASP.NET web application
  2. Add Entity Data Model
  3. Visualize and design the Entity Data Model
  4. Generate Database using the Model
  5. Adding MVC5 controller and view using the EF
  6. Perform CRUD (Create Read Update and Delete) operations
  7. Check the updation of tables and records

Step 1- Create the ASP.NET web application

For this, simply follow the below steps:

  1. Open Visual Studio 2013 and click on ‘New Project’.
  2. With the left menu, select ‘Web’ tab. Within the flyout displayed thereafter, select the option ‘ASP.NET web application’ followed by naming the application as “ModelFirstApproach”. Pls. Refer the screen-shot below:
    Create ASP.NET Web Application
  3. Now, select the value for project template as ‘MVC’ and click on ‘OK” as shown in below screen-shot:
    Choose MVC
    On hitting the ‘OK; button, Visual Studio will automatically generate a new MVC5 web application and add different files and folders to the ‘ModelFirstApproach’ project.

Back to top

Step 2- Add Entity Data Model

Here, you need to add the ADO.NET Entity data model to the created ASP.NET web application. For this, you’ll be required to create an empty model using the below process:

  1. Go to Solution Explorer and right click on ‘Models’ folder, followed by clicking on ADO.NET Entity Data Model as shown in below screen-shot:
    ADO.NET Entity Data Model
  2. Define a model name. In this example, I’ve named it as ‘ModelFirstModel’ as shown below:
    MVC Model
  3. On the proceeding Entity Data Model wizard, simply select ‘Empty Model’ and click on ‘Finish’ as shown below:
    Entity Data Model Wizard
    Upon clicking ‘Finish’, you’ll be able to view the ‘Entity Data Model Designer’ as shown below:
    Entity Data Model Designer

Back to top

Step 3- Visualize and design the Entity Data Model using the Entity Data Model Designer

Adding Entity Model- For this, follow the below procedure:

  1. Right click on ‘Data Model Designer’ and click on ‘Add New’ and ‘Entity’ options as shown in below screen shot:
    Add New Entity
  2. Now, in the Add New Entity wizard, specify a name for the entity as shown below:(In my example, I’ve named it as ‘Books’
    Book Entity
    Clicking on ‘OK’ within the above screen-shot will create a new entity
  3. Add a scalar property to the created entity by simply right clicking on the entity, followed by clicking on ‘Add New’ and ‘Scalar Property’ options as shown below:
    Entity Scalar Property
  4. Now, change the name of the property, followed by adding more scalar properties to the created entity as shown in below screen-shots:
    EDM Scalar Property
    Entity Data Model Properties

Back to top

Step 4- Generate Database using the Model

Once you’re done with creating the entity model, opt for generating database from the same using the steps explained below:

  1. Right click on Data Model Designer Surface and select the option ‘Generate Database from Model’ option from the dropdown list as shown in below screen-shot:
    Data Model Designer Surface
  2. Now, in the next wizard, click on ‘New Connection’ button to connect the app with the database as shown in below screen-shot:
    EDM Connection
  3. In the next Connection Properties wizard, input a name for the server and database. The screen for this will be similar to:
    Connection Properties Wizard
    Clicking on ‘OK’ will create the connection and you’ll be shown this screen:
    Connection Wizard
    Clicking on ‘Next’ within the above screen, you’ll be shown a screen that’s exactly similar to this:
    Summary of Settings
  4. Right click on the script and further click on ‘Execute’ option as shown in below screen-shot:
    Execute Now
    Upon executing the database, you’ll be able to view it in the Server Explorer as shown below:
    Executing the database

Back to top

Step 5- Adding MVC5 controller and view using the Entity Framework

For this, follow the below steps:

  1. The ‘Books’ class is generated in the models folder. Here, all you need to do is simply edit the code with the highlighted one as shown below:

    //------------------------------------------------------------------------------
    //
    // This code was generated from a template.
    //
    // Manual changes to this file may cause unexpected behavior in your application.
    // Manual changes to this file will be overwritten if the code is regenerated.
    //
    //------------------------------------------------------------------------------

    namespace ModelFirstApproach.Models
    {
             using System;
             using System.Collections.Generic;
             using System.ComponentModel.DataAnnotations;

             public partial class Books
             {
                    public int Id { get; set; }

                   [Required(ErrorMessage=”*Required”)]
                   public string Name { get; set; }

                   [Required(ErrorMessage = “*Required”)]
                   public string Author { get; set; }

                   [Required(ErrorMessage = “*Required”)]
                   [Display(Name=”Price(USD)”)]
                   public decimal Price { get; set; }

                   [Required(ErrorMessage = “*Required”)]
                   [Display(Name=”Publised Date”)]
                   public DateTime PublishedDate { get; set; }
              }
    }

    In the above code, I’ve changed the property’s display name.

  2. Now, right click on the Controller and further click on ‘Add’ and then ‘New Scaffolded Item’ as shown in below screen-shot:
    New Scaffolded Item
  3. In the Add Controller wizard, select the option ‘MVC5 Controller using the Entity framework with views’ as shown below:
    MVC5 Controller using EF
    On the above screen, click on ‘Add’ button to reach the screen shown below:
    MVC5 Controller with View
    On the above screen, select model class and data context class, followed by clicking on ‘Add’ button. Once you click on ‘Add’ button, a ‘BooksController class will be generated in the Controller folder along with the generation of Books folder in the Views folder.

Back to top

Step 6- Perform CRUD (Create Read Update and Delete) operations

I’ve segregated this step into specific sections explained below:

  1. Create an Action link to the view. For this go to Views-> Shared-> Layout.cshtml file and edit the code with the one highlighted in the below mentioned code snippet:

    <!DOCTYPE html>
    <html>
    <head>
         <meta charset="utf-8" />
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>@ViewBag.Title - Book Store</title>
         @Styles.Render("~/Content/css")
         @Scripts.Render("~/bundles/modernizr")
    </head>
    <body>
        <div class="navbar navbar-inverse navbar-fixed-top">
           <div class="container">
               <div class="navbar-header">
                   <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                   <span class="icon-bar"></span>
                   <span class="icon-bar"></span>
                   <span class="icon-bar"></span>
                   </button>
                  @Html.ActionLink("Best Books", "Index", "Home", null, new { @class = "navbar-brand" })
               </div>

    <div class="navbar-collapse collapse">

               <ul class="nav navbar-nav">
                     <li>@Html.ActionLink("Home", "Index", "Home")</li>
                     <li>@Html.ActionLink("About", "About", "Home")</li>
                     <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                     <li>@Html.ActionLink("Books", "Index", "Books")</li>
               </ul>
                @Html.Partial("_LoginPartial")
            </div>
         </div>
    </div>
    <div class="container body-content">
            @RenderBody()
             <hr />
             <footer>
                <p>© @DateTime.Now.Year - Book Store</p>
              </footer>
    </div>

    @Scripts.Render(“~/bundles/jquery”)
    @Scripts.Render(“~/bundles/bootstrap”)
    @RenderSection(“scripts”, required: false)

    </body>
    </html>

    Observe the above code carefully and you’ll find that the app name and title have been edited.

  2. For Create operation, you’ll need to implement the below steps:
    • Run the MVC application and on its home page, click on ‘Books’ tab available within the header section as shown below:
      MVC Application Home
    • On the next window, click on ‘Create New’ link for creating a new record. Have a look at this:
      MVC App Index Page
      A ‘form will be displayed on clicking the ‘Create New’ link. Simply enter values for fields viz: Name, Author, Price(USD) and Published Date and hit the ‘Create’ button. Screen for this step looks exactly similar to the one shown below:
      Create Operation in MVC
      Opt for adding multiple records using the procedure explained above.
  3. For Read operation, simply click on Books link and you’ll be able to read all the records available for the same. See this:
    Read Operation in MVC
  4. For Update operation, simply click on the ‘Edit’ link for the record you want to update the details for. You’ll be able to view the details for the respective books record in an editable format. Make the desired alterations and hit the ‘Save’ button to save the changes made to the book.
    Update Operation in MVC
  5. For Delete operation, just click on the ‘Delete’ link available against the record you want to delete from the database. A window like this will appear on your monitor:
    Delete Operation in MVC
    Clicking on ‘Delete’ button will remove the respective record from the database.

Back to top

Step 7- Check the updation of tables and records within the application’s database

You can do this with the help of Server Explorer, following the below mentioned steps:

  1. Open the Model in the Server Explorer
  2. Click on ‘Tables’ folder, followed by a right click on ‘Books’ and a final click on ‘Show Table Data’ option. The screen for this will look exactly similar to the one shown below:
    MVC with Entity Framework
    The records would hence be displayed in the same manner as shown in the below screen-shot:
    ASP.NET MVC5 using Entity Framework 6

That’s all for this ASP.NET MVC post.
Back to top

You can get a comprehensive list of Entity Framework Interview Questions here.

Closing Thoughts
Hope by now you’d have become well familiar with the Model First approach used in ASP.NET MVC5. So, what’s the wait for? Get going with coding marvelous ASP.NET web applications which have the caliber of impressing one and all.

About the Author – Celin Smith
A seasoned web developer with some bona fide writing skills, Celin Smith works at Xicom Technologies Ltd.   Serving Xicom , a leading web development company , Celin basically writes about web & mobile apps, and technologies including Java, .NET, PHP, etc.


Top ASP.NET MVC Jobs

IT Software Developer
Source: Far Bank Enterprises
Details: Developing applications using Microsoft technologies, including C# and ASP.Net MVC. Far Bank Enterprise is seeking a Software Developer to join our IT team on...  More
15 days ago

Bainbridge Island, WA 04-February-2017

.Net Developer
Source: Ramsoft Systems, Inc.
Details: ASP.Net, MVC Framework, C#, Entity Framework. Hope you are doing well....  More
19 days ago

Richmond, VA 23229 31-January-2017

.NET Developer with Microsoft Active Directory
Source: Ramsoft Systems, Inc.
Details: ASP.Net, MVC Framework, C#, Entity Framework. Hope you are doing well....  More
22 days ago

Richmond, VA 23229 28-January-2017

Software Developer II
Source: Almac Group, Inc
Details: C#, .NET 4.5 or higher, Linq, ASP.NET MVC, Visual Studio 2013 or higher. Almac Group is a group of established businesses at the forefront of the Pharmaceutical...  More
3 days ago

Lansdale, PA 19446 17-February-2017

Junior Level .NET Developer
Source: Levi, Ray & Shoup, Inc.
Details: Time to get to work! LRS Consulting Services is seeking a Junior Level .NET Developer for a 3-6 month contract-to-hire opportunity with our client in Central  More
2 days ago

Illinois 17-February-2017

Software Developer
Source: Indeed
Details: Experience with Microsoft *Visual Studio 2013+* and *C# 4.5.* Experience creating *WCF* and *Web API* services. Understanding of *object oriented design* &   More
24 days ago

Redmond, WA 26-January-2017

Software Developer - Operations
Source: Hudl
Details: You’ll likely be working with technologies like React and Bootstrap, C# and ASP.NET MVC, MongoDB, and a number of AWS services....  More
12 days ago

Lincoln, NE 68508 07-February-2017

Junior .NET Developer
Source: SBG Technology Solutions
Details: Must have a clear understanding of ASP.NET MVC, and MVC application design pattern experience. At least five (5) years of development experience, including 4+...  More
5 days ago

Alexandria, VA 22314 14-February-2017

Software Developer
Source: Indeed
Details: *Michigan based applicants ONLY* Equal Opportunity Employer; E-Verify Participant _\*Please do not apply if you are not legally authorized to work in the  More
4 days ago

Lansing, MI 15-February-2017

Software Developer
Source: Indeed
Details: _Experience with Microsoft .NET C# and ASP.NET, MVC, & Entity Framework_. Intellicheck Mobilisa is a publicly-traded technology company located in Jericho, NY...  More
5 days ago

Jericho, NY 14-February-2017

Junior .NET Developer
Source: Publishers Clearing House
Details: Windows Forms, WCF, ASP.NET, MVC. Publishers Clearing House (PCH), headquartered in Port Washington, NY (soon to be Jericho, NY!)....  More
30+ days ago

Port Washington, NY 11050 12-December-2016

Software Developer
Source: Altruista Health
Details: Deep technology experience, including ASP.Net, MVC, C#.Net, SQL Server 2008, and SQL Server 2012. Altruista Health, Inc., is seeking an experienced professional...  More
12 days ago

Reston, VA 20190 07-February-2017

.Net Developer
Source: Indeed
Details: MVC:. Develop web, web services and back-office applications using the newest Microsoft stack of technologies including Net CORE, ASP.NET, MVC, Angular,...  More
2 days ago

Charlotte, NC 17-February-2017

ASP.NET/Angular Developer
Source: Intellisoft Technologies
Details: No new resumes ASP.NET/Angular Developer BlackHawk 700 State Hwy. 121 Bypass Suite 200 Lewisville, Texas 75067 6+ Month Contract Industry leading Client...  More
30+ days ago

Dallas, TX 05-January-2017

Certified Microsoft .NET Developer
Source: Indeed
Details: The project includes .Net MVC web applications with heavy use of JavaScript, jQuery and Kendo UI components....  More
4 days ago

Madison, WI 15-February-2017

.NET Developer
Source: NYC Careers
Details: Experience building full-featured software with ASP.NET MVC, WebForms, VB.NET, SQL and Javascript. The Kings County District Attorney's Office, located in the...  More
4 days ago

Brooklyn, NY 15-February-2017

.Net Developer
Source: Indeed
Details: ASP.NET MVC, JQuery, Entity framework, HTML programming. .Net MVC 4.0 and Strong experience in designing and developing layered web based applications with...  More
18 days ago

Bellevue, WA 01-February-2017

.NET DEVELOPER
Source: Indeed
Details: ASP.NET MVC, JQuery, Entity framework, HTML programming. .Net MVC 4.0 and Strong experience in designing and developing layered web based applications with...  More
18 days ago

Seattle, WA 01-February-2017

Software Engineer C# .Net Developer
Source: MorphoTrust
Details: Responsible for software design and implementation (C#/.Net, ASP.Net MVC, SQL Server, Javascript), testing, debugging, assurance testing, and creation of...  More
30+ days ago

Bloomington, MN 18-January-2017

Software Development Engineer I
Source: Apptio
Details: You: You are a software engineer who strives for excellence in the user’s experience as well as in your technical solutions. You have a curious mind and a...  More
30+ days ago

Bellevue, WA 05-January-2017

NET DEVELOPER - SENIOR (FULL-TIME CONTRACTUAL)
Source: State of Maryland
Details: ASP.NET MVC with Razor. SQL Server 2012, Visual Studio 2015, .NET 4.6 and MVC 5. Development, maintenance, trouble-shooting and debugging of .NET applications...  More
2 days ago

Baltimore, MD 17-February-2017

Developer - Full Stack ASP.NET MVC, C#, SQL Server
Source: Indeed
Details: ASP.NET MVC, C#, SQL Full Stack Server Developer (Austin, Tx)*. Who We Are ...*....  More
2 days ago

Austin, TX 78759 17-February-2017

Mid .Net Developer
Source: Indeed
Details: *Secret Clearance Required!!!!* Current contract until 2020! This highly responsible position involves using established work procedures to analyze, design,  More
5 days ago

Herndon, VA 20171 14-February-2017

Senior Developer
Source: Indeed
Details: Knowledge or experience in ASP.NET, MVC 3+, WCF, ADO.NET. NO C2C PLEASE*....  More
6 days ago

Chicago, IL 60654 13-February-2017

Software Engineer/Developer
Source: ITR (Information Technology Resources)
Details: Candidates demonstrating applied experience with ASP.NET MVC, Java, and Linux will be given extra consideration....  More
30+ days ago

Oak Ridge, TN 08-January-2017

Top 10 Interview Questions and Answers Series:

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest
  • Alius Umbra

    Can you set up an example where you’re using POCO instead of EDMX?