Connecting the MVC Application Using EntityFramework DB-First Approach: Part 3

Introduction

In our first and second attempt to learn MVC, we learned what MVC is. What is separation of concerns? How to create a simple MVC application and perform CRUD operations on the application using LINQ to SQL?

This article focuses on how to perform CRUD operations in MVC application using Entity Framework (an ORM).

The article is an attempt to overcome the confusion related to how to use EntityFramework with MVC applications in a very simple way.

Our Roadmap

Our roadmap remains the same; it is:

    Pre-requisites

    There are a few pre-requisites before we start with the article:

    1. We have running sample application that we created in the second part of the article series.
    2. We have EntityFramework 4.1 package or DLL on our local file system.
    3. We understand how a MVC application is created.

    What is ORM and EntityFramework MVC.jpg?

    The topic isn't that scary as it seems to be. Object Relational Mapping (ORM) is basically an approach for storing data from domain/entity objects to a relational database in an automated way without writing much code. A true ORM is independent of what database server we refer to, the code underlying ORMs is database independent and can run with any database server having a similar database with a structure needed by the application. ORM has 3 main parts: Entity class objects, Relational database objects and information on how domain objects map to relational database objects, in other words tables, views & Stored Procedures. ORM helps us to keep our database design separate from our domain class design. This makes our application maintainable and extendable. It also automates standard CRUD operation (Create, Read, Update & Delete) so the developer doesn't need to code them manually.

    Now let's have a look at the standard definition of Entity Framework given by Microsoft:

    "The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write. Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects. The Entity Framework's ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals."

    In simple language, Entity Framework is an Object/Relational Mapping (ORM) framework. It is an enhancement to ADO.NET, an upper layer to ADO.Net that gives developers an automated mechanism for accessing & storing the data in the database.

    Hope this gives a glimpse of an ORM and EntityFramework.

    EntityFramework Architecture

    Let's have a look at the architecture of EntityFramework:

    MVC1.jpg

    Our Web Application interacts with Entity Data Model (Entity Framework), that acts as an interface between ADO.Net Provider and database, fetches/saves data in the same flow as described in the figure.

    Perform CRUD operations using EntityFramework on MVC application

    Open the existing Learning MVC application that we created using LINQ to SQL.

    MVC2.jpg

    I have made a few changes in the existing application, just to make it easy to understand when we implement EntityFramework in it.

    1. Changed the model class name from User to UserList,

    1. namespace LearningMVC.Models  
    2. {  
    3.     #region User Model...  
    4.     /// <summary>  
    5.     /// User Model Class, purposely used for populating views and carry data from database.  
    6.     /// </summary>  
    7.     public class UserList  
    8.     {  
    9.        #region Automated Properties  
    10.         public int UserId { getset; }  
    11.         public string FirstName { getset; }  
    12.         public string LastName { getset; }  
    13.         public string EMail { getset; }  
    14.         public string Address { getset; }  
    15.         public string PhoneNo { getset; }  
    16.         public string Company { getset; }  
    17.         public string Designation { getset; }  
    18.         #endregion  
    19.     }  
    20.     #endregion  
    21. }
    2. Changed the Solution name from LearningMVC to LearningMVCWithEF.

    Procedure

    1. Open the application, modify it with the changes given above.

    2. Delete the MyDBML.dbml class from the solution.

    3. Do not build the solution now, it will result in an error, since we have removed the dbml file, so controller method accessing the dbml file will throw compile time errors.

    4. Go to the project and right-click "Add new item", select "Data" in the installed templates and add ADO.Nety EntityDataModel to the application.

    MVC3.jpg

    Name it EFDataModel.edmx.

    5. A new window will be opened to choose model contents:

    MVC4.jpg

    Since we are following Database First approach, select "Generate from Database".

    6. Choose the connection and give the name to the connection string as MVCEntities as shown in the figure, click Next.

    MVC5.jpg

    7. Provide connection details to the existing database that we used for our existing application, the database name was MVC.

    If you don't have an existing one then create a new one with the attached database script files.

    MVC6.jpg

    8. Choose database objects, we have only one table , so choose that one as shown in the following figure:

    MVC7.jpg

    Give the model namespace "MVCModel".

    9. We get in our solution one guest, Entity Data Model that we saw in Entity Framework Architecture above.

    MVC8.jpg

    10. In web.config you will see that a new connection string has been added. Now you can comment/delete the old connection string of LINQ to SQL,

    MVC9.jpg

    11. Now to generate Strongly Typed Entity Model Classes (taken from a blog).

    We'll be working with the strongly typed entity classes now. The Entity Data Model designer uses a code generator in Visual Studio called the Text Template Transformation Toolkit (T4). Entity Framework will automatically generate a User class. The code generator will now create a class based on our Entity Data Model.

    By default, the designer uses a template that results in entity classes that inherit from Entity Framework's EntityObject and a container class that inherits from EF's ObjectContext.

    These base classes can be cumbersome to work with for a number of reasons. While the ObjectContext is extremely useful when you need a lot of control over Entity Framework's behavior, the lighter weight DbContext provides access to the most commonly needed tasks and simplifies your coding.

    Microsoft provides a number of alternative T4 templates for generating classes from the EDM. When you installed the EF 4.1, a template for creating simpler classes including the DbContext was added to Visual Studio. Let's tell the designer to use this template instead of the default.
    • Right-click on the model's designer surface.
    • From the context menu, choose "Add Code Generation Item".
    • In the Add New Item dialog that opens, select Code from the list of installed templates types on the left.
    • Choose the ADO.NET DbContext Generator then click the "Add" button.

    MVC10.jpg

    Two new files will be listed in Solution Explorer, Model1.Context.tt and Model1.tt. These are template files. Expand the templates to see the generated classes as shown in the following figure:

    MVC11.jpg

    12. When we open these two new guests, we see the context class to access model and model class for our user entity is already created, with full code.

    MVC12.jpg

    Have you noticed that we haven't written a single line of code by our hand, this is the revolution that EntityFramework has developed. Let's give a round of applause to our smart work.

    MVC13.jpg

    Time to write some code now

    Until now we have not written a single line of code, but to access the context class, we need to change the logic from accessing LINQ to SQL data context to EntityFramework data context in the controller we created earlier in the second part of the tutorial.

    Procedure

    Step 1

    Bind all our views with UserList class, later it was user class, but we changed that to UserList class (remember????).

    Step 2


    Open the controllers, change the access mechanism of the context class as shown below for the example Index Action.

    Earlier:

    1. public ActionResult Index()  
    2. {  
    3.     var dbContext = new MyDBDataContext();  
    4.     var userList = from user in dbContext.Users select user;  
    5.     var users = new List<LearningMVC.Models.User>();  
    6.     if (userList.Any())  
    7.     {  
    8.         foreach (var user in userList)  
    9.         {  
    10.             users.Add(new LearningMVC.Models.User() { UserId = user.UserId, Address = user.Address, Company = user.Company, FirstName =    user.FirstName, LastName = user.LastName, Designation = user.Designation, EMail = user.EMail, PhoneNo = user.PhoneNo });  
    11.         }  
    12.     }  
    13.     ViewBag.FirstName = "My First Name";  
    14.     ViewData["FirstName"] = "My First Name";  
    15.     if(TempData.Any())  
    16.     {  
    17.         var tempData = TempData["TempData Name"];  
    18.     }  
    19.     return View(users);  
    20. } 

    Now:

    1. public ActionResult Index()  
    2. {  
    3.     var dbContext = new MVCEntities() ;  
    4.     var userList = from user in dbContext.Users select user;  
    5.     var users = new List<LearningMVC.Models.UserList>();  
    6.     if (userList.Any())  
    7.     {  
    8.         foreach (var user in userList)  
    9.         {  
    10.             users.Add(new LearningMVC.Models.UserList() { UserId = user.UserId, Address = user.Address, Company = user.Company, FirstName = user.FirstName, LastName = user.LastName, Designation = user.Designation, EMail = user.EMail, PhoneNo = user.PhoneNo });  
    11.         }  
    12.     }  
    13.     ViewBag.FirstName = "My First Name";  
    14.     ViewData["FirstName"] = "My First Name";  
    15.     if(TempData.Any())  
    16.     {  
    17.         var tempData = TempData["TempData Name"];  
    18.     }  
    19.     return View(users);  
    20. }   

    You can see, we just had to change the access mechanism, merely change 2-3 lines, and not anything in the logic of the application.

    Step 3

    Likewise do the same for all the actions. I am not showing how to do that here, but you can compare the source code and now you can do it by yourself.

    Step 4

    Note that the LINQ to SQL context class uses the InsertOnSubmit()/DeleteOnSubmit() and SubmitChanges() methods for insert, update and delete but the EF context class uses Add() and SaveChanges(). So do it skillfully when required.

    Step 5

    All set now, rebuild your application, and you'll not get a single error. Now ready to run.

    Step 6

    When you run the application, it runs as it was running previously and now you can perform CRUP operations as an end user to the application, and test the application.

    MVC14.jpg

    Nothing more dude, we are done with Entity framework's database first approach now. You can applause again, and take some rest.

    MVC15.jpg

    Conclusion

    We have already moved to one step on the advanced level of CRUD operations in MVC. There is more to learn in MVC and Entity Framework, that we'll be covering in upcoming articles. In this article we mastered how to perform CRUD operations in an MVC application using EntityFramework's database first approach. The next article will focus on my favorite CodeFirst approach.


    Similar Articles