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; }

                   public string Name { get; set; }

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

                   [Required(ErrorMessage = “*Required”)]
                   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>
         <meta charset="utf-8" />
         <meta name="viewport" content="width=device-width, initial-scale=1.0">
         <title>@ViewBag.Title - Book Store</title>
        <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>
                  @Html.ActionLink("Best Books", "Index", "Home", null, new { @class = "navbar-brand" })

    <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>
    <div class="container body-content">
             <hr />
                <p>© @DateTime.Now.Year - Book Store</p>

    @RenderSection(“scripts”, required: false)


    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.


Developer, C#, .NET, MVC
Source: Logic20/20
Details: Developer, C#, .NET, MVC. C#, .NET framework (ASP.NET MVC, Entity Framework). Solid knowledge of C#, .NET framework (ASP.NET MVC, Entity Framework)....  More
13 days ago

Seattle, WA 98115 13-June-2017

Dot Net Developer
Source: Indeed
Details: ASP.NET MVC, JQuery, Entity framework, HTML programming. Develop enterprise web or desktop applications using *Microsoft .NET, ASP.NET, C#, application...  More
18 days ago

Redmond, WA 07-June-2017

Principal Engineer
Source: Indeed
Details: C#, .NET, ASP.NET MVC, WCF, Rest, WebAPI, HTML5, AJAX, JSON, JQuery, ServiceBus, RabbitMQ, TeamCity and similar....  More
30+ days ago

Austin, TX 22-May-2017

ASP.NET MVC Web Developer
Source: Cardinal Intellectual Property, Inc
Details: ASP.NET MVC Web Developer. Strong or expert knowledge of C#, JQuery, JavaScript, Knockout JS, ASP.NET MVC, MSSQL....  More
2 days ago

Evanston, IL 23-June-2017

Senior .Net Developer
Source: Indeed
Details: Sitecore (including Helix and MVC), C#/.NET, ASP.NET MVC, NPM, jQuery, CSS, SASS, GIT & SVN, CI, SQL, DB2, and REST service architecture....  More
4 days ago

Wilton, CT 21-June-2017

.NET MVC Web Developer
Source: R. Watson & Associates, Inc.
Details: Experience with ASP.NET MVC, SQL, HTML and JavaScript at a minimum. We are looking to expand our team by hiring a .NET MVC Web Developer....  More
10 days ago

Talent, OR 16-June-2017

.NET Developer
Source: Inforeem
Details: 3.AngularJS, ASP.NET MVC, JQuery, HTML5. We are looking for strong profiles in .NET/C#, MVC (data Structure, Algorithm), SQL queries....  More
24 days ago

Redmond, WA 02-June-2017

ASP.NET MVC Developer
Source: Net ESolutions Corporation (NETE)
Details: Design and develop new features and/or maintains existing applications developed on ASP.NET MVC. NETE is seeking a highly motivated, flexible, organized, and...  More
23 days ago

McLean, VA 03-June-2017

C# .Net Developer (Locals Only)
Source: Indeed
Details: 3.AngularJS, ASP.NET MVC, JQuery, HTML5. 1.Good in C# and Microsoft .Net....  More
3 days ago

Redmond, WA 22-June-2017

C# .Net Developer
Source: Indeed
Details: Responsibilities include: Rewrite an existing COTs system in accordance with CMS’ Agile XLC framework on site at Security Blvd. Under the guidance of the  More
3 days ago

Windsor Mill, MD 21244 22-June-2017

.Net Developer - Web Services - Web API - SQL
Source: Indeed
Details: 4 to 7+ years experience with software design and development (including the Microsoft application development framework) preferably C#, ASP.Net, ASP.Net MVC....  More
9 days ago

Minneapolis, MN 16-June-2017

Xamarin Dotnet/.Net Developer
Source: Indeed
Details: Strong knowledge and working experience of NET MVC. Solid experience on C#, Xamarin - Xamarin including Xamarin.iOS and Xamarin.Android, JavaScript, Mobile...  More
9 days ago

Miami, FL 16-June-2017

.NET Software Developer Fin Tech
Source: Indeed
Details: Experience with ASP.NET MVC. Would you enjoy working in a cutting edge C# environment and programming with technologies like C# 5.0, MVC 5, ASP.NET Core and...  More
9 days ago

Evanston, IL 16-June-2017

.NET Software Developer - Cambridge, MA
Source: Indeed
Details: Exposure to ASP.NET MVC framework:. Good understanding and exposure to ASP.NET MVC framework. .NET Software Developer....  More
11 days ago

Cambridge, MA 15-June-2017

C# .Net Developer
Source: Indeed
Details: MVC:. Solid understanding of MVC architecture and frameworks. Experience in enterprise web application development using Microsoft technologies(C#, ASP.NET MVC,...  More
12 days ago

Santa Clara, CA 13-June-2017

Software Developer
Source: Indeed
Details: Experience with Asp.net MVC, Razor, .Net Core, Html, CSS, XML, XSLT, XPath, AJAX, Web API (is a plus). Software Developer (Mid-Level)*....  More
3 days ago

Austin, TX 78730 22-June-2017

Software Developer
Source: Indeed
Details: Knowledge in Visual Studio 2005-2013 and .NET Framework 2.0 - 4.5.1, ASP.NET MVC 5.0, VB 6.0/.NET, C, C++, C#, Java, Tomcat, Transact-SQL, HTML, XML, JavaScript...  More
4 days ago

San Juan, PR 21-June-2017

ASP.NET Web Developer
Source: Sandhills Publishing
Details: ASP.Net MVC Framework, Object Oriented Programming, Web Services and RESTful APIs, XML, MS SQL, HTML, CSS, TFS or Version Control familiarity....  More
5 days ago

Lincoln, NE 20-June-2017

Applications Developer 3 - .NET
Source: Metropolitan Council
Details: Experience with any JavaScript based MVC or MVVM framework, such as:. Work in an environment that allows you to have a life outside of work and does NOT require...  More
17 days ago

Minneapolis, MN 08-June-2017

Software Development Engineer - Full Stack - Contract
Source: Neal Analytics
Details: Middle tier (ASP.NET MVC / Java). Familiar with MVC, Entity Framework, ASP.NET. We are supporting a well-known cloud platform for one of the largest software...  More
26 days ago

Redmond, WA 31-May-2017

SQL Lead Developer
Source: Indeed
Details: Understanding of ASP.NET MVC 5 including Bootstrap, Razor views and view models, as well as controllers and models. Are you a SQL Wizard?*....  More
9 days ago

Mooresville, NC 28117 16-June-2017

Junior Software Engineer
Source: Indeed
Details: Oracle 11g (or higher), SQL Server 2012 (or higher), AngularJS framework, HTML/HTML5, ASP.Net / ASP.Net MVC. Responsibilities of the Junior Software Engineer:....  More
2 days ago

Prescott Valley, AZ 86314 23-June-2017

Launch and Range Subject Matter Expert (Software Engineer)
Source: Sigmatech, Inc.
Details: Experience in software development utilizing C#, MVC, JavaScript, .NET., Visual Studio, and SQL. Proficiency in C#, ASP.NET MVC, Web API, MSSQL Server, MySQL,...  More
3 days ago

Colorado Springs, CO 80901 22-June-2017

Software Developer
Source: Indeed
Details: .NET Stack experience (C#, ASP.NET MVC, MS SQL Server). We are seeking a talented and motivated software developer to join our development team....  More
9 days ago

San Diego, CA 16-June-2017

Software Engineer. Net
Source: Indeed
Details: JQuery, SSRS, Design Pattern, ASP.NET MVC, and UML, Microsoft Test Manager. C#, ASP.NET with MVC, SQL Database 2012/2014, and Business Analysis, Report Services...  More
5 days ago

Boca Raton, FL 33487 21-June-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?