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

Developer - Web
Source: Geocaching
Details: Proficient with ASP.NET, MVC, REST, WCF, Web API and scalable service oriented architectures. About Geocaching HQ....  More
16 days ago

Seattle, WA 98103 07-January-2017

C# Software Developer (Web Services & API)
Source: Indeed
Details: C#, ASP.NET, MVC or better required, Java/Node.js a plus. If you’re looking for a rewarding career with a dynamic and fast-growth healthcare software company,...  More
10 days ago

Seattle, WA 12-January-2017

.Net Developer
Source: Indeed
Details: .Strong Experience developing MVC applications using ASP.Net MVC. .4+ years experience in software engineering....  More
30+ days ago

Redmond, WA 30-November-2016

Sr. Web Developer (.Net/SharePoint)
Source: V3Main Technologies Inc.
Details: ASP.NET , VB.NET , C#, MVC, Entity Framework, Ajax, Bootstrap, JSON, jQuery, Knockout, HTML5, CSS3, IIS, SSL, TLS, SSH, TFS, FTP, XML, XLST, Classic ASP,...  More
6 days ago

Houston, TX 16-January-2017

.NET Developer
Source: TS Solutions
Details: ASP.NET MVC (4), C#, Azure, SQL Server. TokuSaku (TS) Solutions is looking for .NET developer with numerous bolt-on skill sets to help with our list of direct...  More
3 days ago

Seattle, WA 19-January-2017

.NET Web Application Developer
Source: NIC
Details: MVC. In-depth experience with C#, ASP.NET and MVC. Leading Web Services and E-Commerce company seeking two full-time .NET Web Application Developers to...  More
10 days ago

Frankfort, KY 13-January-2017

.NET Web Developer
Source: NIC
Details: MVC. Leading Web Services and E-Commerce company seeking a full-time .NET Web Application Developer to complement our growing team in Jackson, Mississippi....  More
11 days ago

Jackson, MS 11-January-2017

.NET Web Developer
Source: Springbox
Details: Experience with (.NET) MVC, MVP, MVVM architecture design and an understanding of design patterns, in particular OO/IoC/DI....  More
13 days ago

Austin, TX 78701 10-January-2017

Sr. Web Developer & Designer
Source: Indeed
Details: Expertise in most of the following –Web API (MS ASP.Net), MVC, WCF, HTML5, CSS, JavaScript, JSON, SOAP, REST, JQuery, .Net Framework, C#, Web Services....  More
2 days ago

Austin, TX 73301 20-January-2017

Web Developer
Source: Indeed
Details: Programming experience ASP.Net MVC, JavaScript and C# required. Securitas Security Services USA, Inc....  More
2 days ago

Westlake Village, CA 20-January-2017

.NET Web Developer
Source: Blue Earth Interactive
Details: Experience with popular web application frameworks, such as Kendo/Telerik MVC. About Blue Earth:....  More
13 days ago

Saint Paul, MN 55101 09-January-2017

Web Developer/Programmer
Source: Indeed
Details: Don't miss this great opportunity to join a leader in the equipment business at Messick’s in Elizabethtown. We are looking for a *C#* *.NET Web Engineer* to  More
4 days ago

Elizabethtown, PA 18-January-2017

Windows C# .NET MVC Web Portal Developer in Ft. Lauderdale,FL
Source: Indeed
Details: Have Experience in MVC 4.0 and 5.0 and capable of working in projects with MVC. Windows C# .NET MVC Web Portal Developer - Contract....  More
5 days ago

Fort Lauderdale, FL 18-January-2017

.Net Full Stack Developer
Source: Sonsoft Inc
Details: At least 4 years of product development experience in Dot Net technologies (C#, ASP.Net, MVC, MVVM, WCF, SQL Server)....  More
5 days ago

Redmond, WA 18-January-2017

Entry Level Developer
Source: Fairfax Data Systems
Details: Must possess a strong desire to work with different programming languages like .Net (C#, VB.Net/asp.net mvc), Java/J2EE, etc., and learn new technologies like...  More
30+ days ago

New Milford, CT 06776 13-December-2016

.NET Web Developer (Denver, CO) (Long-term Contract)
Source: Chipotle Mexican Grill
Details: ASP.Net MVC and Razor; .NET Web Developer (Denver, CO) (Long-term Contract) (17000744) Description....  More
17 days ago

Denver, CO 05-January-2017

ASP.NET / C# Software Developer (Web Services & API)
Source: Indeed
Details: C#, ASP.NET, MVC or better required, Java/Node.js a plus. The Software Developer is an experienced engineer that uses C#, ASP.NET, MVC to build web services,...  More
7 days ago

Tacoma, WA 16-January-2017

Web Developer
Source: Indeed
Details: Programming experience ASP.Net MVC, JavaScript and C# required. Securitas Secuirty Services USA, Inc....  More
9 days ago

Westlake Village, CA 13-January-2017

Wellness Programs Web Developer (Consultant)
Source: Indeed
Details: Knowledge and experience developing custom applications using MVC is essential. Develop web applications using VISUAL STUDIO.NET, ASP.NET, MVC, ADO.NET, XML,...  More
9 days ago

Brooklyn, NY 11201 13-January-2017

Full Stack .NET Developer (C#/JavaScript/SQL/Web Services)
Source: CareWorks Tech
Details: This position will: Develop and support web, middleware and database applications for internal and external deployment. Develop, implement and test project...  More
10 days ago

Columbus, OH 12-January-2017

C# ASP.Net Web Developer
Source: Indeed
Details: Experience with various web technologies, such as HTML, CSS, AJAX, JQuery, JavaScript, AngularJS, Bootstrap, XML, ASP.NET, MVC, WebForms, Web Services, IIS....  More
10 days ago

Irvine, CA 12-January-2017

.Net Full Stack Developer
Source: Sonsoft Inc
Details: At least 4 years of product development experience in Dot Net technologies (C#, ASP.Net, MVC, MVVM, WCF, SQL Server)....  More
5 days ago

Bellevue, WA 18-January-2017

Front End Web Developer
Source: Indeed
Details: *Title: * Senior Web Developer *Reports to: * Digital Channel Manager *Status: * Full-time, exempt *Location: * Boston It takes talent to be the world's  More
12 days ago

Boston, MA 10-January-2017

C# .NET Web Developer - Green Bay, WI or Indianapolis, IN
Source: UnitedHealth Group
Details: Candidates must have strengths in C#, a clear understanding of ASP.NET MVC. Welcome to one of the toughest and most fulfilling ways to help....  More
26 days ago

Indianapolis, IN 46218 28-December-2016

Jr .Net Developer
Source: Indeed
Details: Familiar with Web-API and REST in the ASP.NET MVC world. Professional job experience with C# and ASP.NET MVC (not just ASP.NET web forms). Full time/Long Term*....  More
24 days ago

Redmond, WA 29-December-2016

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?