Click here to Skip to main content
15,868,016 members
Articles / Web Development / HTML

Learning MVC - Part 3: Creating MVC Application & Perform CRUD Operations Using EntityFramework

Rate me:
Please Sign up or sign in to vote.
4.92/5 (44 votes)
17 Mar 2015CPOL7 min read 126.6K   17.3K   105   26
How to create MVC application and perform CRUD operations using EntityFramework

Introduction

In our first and second attempt to learn MVC, we learnt what is MVC, 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 by the use of an ORM (Entity Framework).

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

Our Roadmap 

Our roadmap remains the same:

Pre-requisites

There are 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 MVC application is created.

What is ORM and EntityFramework Image 1?

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 and storing the data in the database.

Hope this gives a glimpse of an ORM and EntityFramework.

EntityFramework Architecture

Let’s have a glance over the architecture of EntityFramework:

 Image 2

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.

Image 3

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

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

2. Changed the Solution name from LearningMVC to LearningMVCWithEF

.

Steps to Follow

  1. Open the application, modify it by the above given changes.
  2. Delete the MyDBML.dbml class from the solution.
  3. Do not build the solution now, it will result in an error, as we have removed the dbml file, so controller method accessing the dbml file will throw compile time errors.
  4. Go to project, right click and add new item, select Data in installed templates and add ADO.NET EntityDataModel to the application.

    Image 4

    Name it EFDataModel.edmx.

  5. New window will be opened to choose model contents, since we are following Database First approach.

    Image 5

    Select generate From Database.

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

    Image 6

  7. Provide connection details to the existing database, that we used for our existing application, database name was MVC. If you don’t have an existing one, create a new one with the attached db script files.

    Image 7

  8. Choose data base objects, we have only one table, so choose that one as shown in the figure, give model namespace as MVCModel.

    Image 8

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

    Image 9

  10. In web.config, you can see a new connection string is added. Now you can comment/delete old connection string of LINQ to SQL.

    Image 10

  11. Generating 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 now will 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 which 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.

    Image 11

    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:

    Image 12

  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.

    Image 13

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

    Image 14

Time to write some code now

Till 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.

Steps to Follow

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 context class as shown below, for e.g., Index Action.

Earlier
C#
public ActionResult Index()
  {
      var dbContext = new MyDBDataContext();
      var userList = from user in dbContext.Users select user;
      var users = new List<LearningMVC.Models.User>();
      if (userList.Any())
      {
          foreach (var user in userList)
          {
              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 });
          }
      }
      ViewBag.FirstName = "My First Name";
      ViewData["FirstName"] = "My First Name";
      if(TempData.Any())
      {
          var tempData = TempData["TempData Name"];
      }
      return View(users);
  }
Now
C#
public ActionResult Index()
        {
            var dbContext = new MVCEntities() ;
            var userList = from user in dbContext.Users select user;
            var users = new List<LearningMVC.Models.UserList>();
            if (userList.Any())
            {
                foreach (var user in userList)
                {
                    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 });
                }
            }
            ViewBag.FirstName = "My First Name";
            ViewData["FirstName"] = "My First Name";
            if(TempData.Any())
            {
                var tempData = TempData["TempData Name"];
            }
            return View(users);
        }

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

Step 3: Likewise, do the same for all the Actions. I am not showing how to do here, but you can compare the source codes and now can do by yourself.

Step 4: Note LINQ to SQL context class uses InsertOnSubmit()/DeleteOnSubmit() and SubmitChanges() method for Insert, update, Delete but EF context class uses .Add(), .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.

Image 15

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

Image 16 

Conclusion

We have already moved to one step on 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 MVC application using EntityFramework’s database first approach, the next article will focus on my favourite CodeFirst approach.

Happy coding :) 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect https://codeteddy.com/
India India
Akhil Mittal is two times Microsoft MVP (Most Valuable Professional) firstly awarded in 2016 and continued in 2017 in Visual Studio and Technologies category, C# Corner MVP since 2013, Code Project MVP since 2014, a blogger, author and likes to write/read technical articles, blogs, and books. Akhil is a technical architect and loves to work on complex business problems and cutting-edge technologies. He has an experience of around 15 years in developing, designing, and architecting enterprises level applications primarily in Microsoft Technologies. He has diverse experience in working on cutting-edge technologies that include Microsoft Stack, AI, Machine Learning, and Cloud computing. Akhil is an MCP (Microsoft Certified Professional) in Web Applications and Dot Net Framework.
Visit Akhil Mittal’s personal blog CodeTeddy (CodeTeddy ) for some good and informative articles. Following are some tech certifications that Akhil cleared,
• AZ-304: Microsoft Azure Architect Design.
• AZ-303: Microsoft Azure Architect Technologies.
• AZ-900: Microsoft Azure Fundamentals.
• Microsoft MCTS (70-528) Certified Programmer.
• Microsoft MCTS (70-536) Certified Programmer.
• Microsoft MCTS (70-515) Certified Programmer.

LinkedIn: https://www.linkedin.com/in/akhilmittal/
This is a Collaborative Group

779 members

Comments and Discussions

 
BugIn Downloaded SourceCode of Part-3: In MyController.cs class Post Method Delete you have use Add instead of Remove Pin
Dharmesh .S. Patil9-Jul-15 20:07
professionalDharmesh .S. Patil9-Jul-15 20:07 
GeneralVery Nice Article Pin
Vikas Sharma1-Jul-15 23:46
professionalVikas Sharma1-Jul-15 23:46 
GeneralRe: Very Nice Article Pin
Akhil Mittal2-Jul-15 0:02
professionalAkhil Mittal2-Jul-15 0:02 
QuestionCan you tell more Specifically advantage of EF in MVC compare to Part-2 ? Pin
Dharmesh .S. Patil1-Jul-15 23:33
professionalDharmesh .S. Patil1-Jul-15 23:33 
AnswerRe: Can you tell more Specifically advantage of EF in MVC compare to Part-2 ? Pin
Akhil Mittal2-Jul-15 0:06
professionalAkhil Mittal2-Jul-15 0:06 
GeneralRe: Can you tell more Specifically advantage of EF in MVC compare to Part-2 ? Pin
Dharmesh .S. Patil2-Jul-15 0:18
professionalDharmesh .S. Patil2-Jul-15 0:18 
GeneralRe: Can you tell more Specifically advantage of EF in MVC compare to Part-2 ? Pin
Akhil Mittal2-Jul-15 0:19
professionalAkhil Mittal2-Jul-15 0:19 
QuestionMVCEntities() not recognized by compiler Pin
Brittle161827-Mar-15 1:44
Brittle161827-Mar-15 1:44 
AnswerRe: MVCEntities() not recognized by compiler Pin
Akhil Mittal30-Mar-15 0:27
professionalAkhil Mittal30-Mar-15 0:27 
GeneralRe: MVCEntities() not recognized by compiler Pin
Brittle161831-Mar-15 20:41
Brittle161831-Mar-15 20:41 
GeneralRe: MVCEntities() not recognized by compiler Pin
Akhil Mittal1-Apr-15 18:37
professionalAkhil Mittal1-Apr-15 18:37 
QuestionAmbiguous methods MVCEntities Pin
Member 109032691-Jul-14 2:31
Member 109032691-Jul-14 2:31 
AnswerRe: Ambiguous methods MVCEntities Pin
Akhil Mittal1-Jul-14 2:41
professionalAkhil Mittal1-Jul-14 2:41 
QuestionMessage Closed Pin
30-Jun-14 23:43
Member 1090326930-Jun-14 23:43 
AnswerRe: MVCEntities not recognized Pin
Akhil Mittal1-Jul-14 0:09
professionalAkhil Mittal1-Jul-14 0:09 
GeneralMy vote of 5 Pin
Júnior Pacheco30-Aug-13 6:32
professionalJúnior Pacheco30-Aug-13 6:32 
GeneralRe: My vote of 5 Pin
Akhil Mittal30-Aug-13 22:27
professionalAkhil Mittal30-Aug-13 22:27 
QuestionGreat!!! Pin
dineshgupta11124-Aug-13 9:24
dineshgupta11124-Aug-13 9:24 
AnswerRe: Great!!! Pin
Akhil Mittal25-Aug-13 23:15
professionalAkhil Mittal25-Aug-13 23:15 
Thanks Dinesh
Thanks
Do not forget to comment and rate the article if it helped you by any means Smile | :) ...
For any technical requirement related to .net ,OOPS,C# and design patterns contact me on akhil.mittal20@gmail.com

AnswerRe: Great!!! Pin
Akhil Mittal18-May-15 18:54
professionalAkhil Mittal18-May-15 18:54 
GeneralMy vote of 5 Pin
CodeLancer8-Aug-13 1:08
CodeLancer8-Aug-13 1:08 
GeneralMy 5+ Pin
gauravupadhyay31-Jul-13 2:17
gauravupadhyay31-Jul-13 2:17 
GeneralRe: My 5+ Pin
Akhil Mittal31-Jul-13 4:00
professionalAkhil Mittal31-Jul-13 4:00 
QuestionSuggestion Pin
mellospank28-Jul-13 23:14
mellospank28-Jul-13 23:14 
AnswerRe: Suggestion Pin
Akhil Mittal26-Aug-13 0:04
professionalAkhil Mittal26-Aug-13 0:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.