Learning MVC Part 3 Creating MVC Application with EntityFramework
1. Learning MVC-Part 2
Creating MVC Application&
Perform CRUD operationsusing Entity Framework
Introduction:
In our firstand second attempt to learn MVC, we learnt, what is MVC?, whatis separation of concerns?, how to create
a simple MVC application and performCRUD operations on the application using LINQ to SQL.
My this article focuses on how to performCRUD operations in MVC application by the use of an ORM(Entity Framework).
The article is an attempt to overcomethe confusion related to how to use EntityFramework with MVCapplication in a very simple way.
Our Roadmap:
Our roadmap remains same,
Part1: Introduction to MVC architecture and Separation of Concerns.
Part 2: Creating MVC Application from scratch and connecting it with databaseusing LINQ to SQL.
Part 3: Connecting the MVC Applicationwiththe helpof EntityFramework DB-First approach.
Part 4: Connecting the MVC Application with the help of EntityFramework Code-Firstapproach.
Part 5: Implementing Repository Pattern in MVC Application with EntityFramework.
Part 6: Implementing a generic Repository Pattern and Unit Of Work pattern in MVCApplication with EntityFramework.
Pre-requisites:
There are few pre-requisites beforewe start with the article,
1. We have running sample application that wecreated in second part of the article series.
2. We have EntityFramework 4.1 packageor dll on our local file system.
3. We understand how MVC application is created.
2. What is ORM and EntityFramework ?
The topic isn’tthat scary as it seems to be.ORM(ObjectRelational Mapping) is basically an approach for storing data from
domain/entity objects to relational databasein an automated way withoutwriting much code. A true ORM is independent of what
database server werefer to, the code underlying ORM’s is databaseindependent and can run with any databaseserver having similar
database with a structureneeded by the application.ORM has 3 main parts: Entity class objects, Relational db objects and information
on how domain objects maps to relational db objects i.e. tables, views & storedprocedures. ORMhelps us to keep our database design
separate fromour domain class design. This makes our application maintainable and extendable. Italso automates standard CRUD
operation (Create, Read, Update & Delete) so developer doesn’t require to code them manually .
Now let’s have a look on standard definition of Entity Framework given by Microsoft:
“The Microsoft ADO.NETEntity Framework isan Object/Relational Mapping (ORM) framework that enablesdevelopersto work
with relational data asdomain-specific objects, eliminating theneed for most of the data access plumbing code that developers
usually need to write. Using the Entity Framework, developersissue queries using LINQ, then retrieveand manipulatedata as
strongly typed objects. The Entity Framework’sORM implementation providesserviceslikechangetracking, identity resolution, lazy
loading, and query translation so that developerscan focus on their application-specific businesslogic rather than thedata access
fundamentals.”
In a simple language, Entity framework is an Object/Relational Mapping (ORM) framework. Itis 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 havea glance over the architecture of EntityFramework,
3. Our Web Application interacts with Entity Data Model (Entity Framework), thatacts as an interface between ADO.NetProvider and
database, fetches/saves data in the sameflow as described in the figure.
Perform CRUD operations using EntityFramework on MVC application:
Open the existing Learning MVC application that wecreated using LINQ to SQL,
4. I have made few changes in the existing application, justto make it easy to understand when we implement EntityFramework in it.
1.Changed the model class name from User to UserList,
3. namespace LearningMVC.Models
5. 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 fromLearningMVCto LearningMVCWithEF.
Steps toFollow:
1.Open the application, modify it by abovegiven changes.
2.Delete the MyDBML.dbmlclass fromthe 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.Goto projectright click and add new item, select Data in installed templates and add ADO.Nety EntityDataModelto the application,
7. Since we are following Database First approach, select generate From Database.
6.Choose the connection and give the name to connection string as MVCEntities as shown in the figure, click next.
8. 7.Provideconnection details to the existing database, that weused for our existing application, databasename was MVC.
If you don’t haveexisting one, create a new one with the attached db scriptfiles.
9. 8. Choose data baseobjects, we have only one table , so choosethat one as shown in figure,
10. Give model namespace as MVCModel.
9.Weget in our solution one guest,Entity Data Model that we saw in Entity Framework Architectureabove,
11. 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,
12. 11. Generating Strongly Typed Entity Model Classes:(taken froma blog)
We’ll be working with the strongly typed entity classes now. The Entity Data Model designer uses a code generator in VisualStudio
called the Text Template Transformation Toolkit (T4). Entity Framework willautomatically generate a User class. The code generator
nowwillcreate a class based on our Entity Data Model.
13. By default, the designer uses a template that results in entity classes that inherit fromEntity Framework’s EntityObjectand a container
class which inherits fromEF’s ObjectContext.
These base classes can be cumbersometo work with for a number of reasons. While the ObjectContextis extremely useful when you
need a lot of control over Entity Framework’s behavior, thelighter weight DbContext provides access to the mostcommonly needed
tasks and simplifies your coding.
Microsoftprovides a number of alternative T4 templates for generating classes fromthe 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.
Fromthe context menu, chooseAdd Code Generation Item.
In the Add New Itemdialog that opens, select Code fromthe list of installed templates types on the left.
Choosethe ADO.NETDbContext Generator then click the Add button.
14. 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 following figure,
15. 12. When weopen 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,
16. Have you noticed that we have’nt written a single line of code by our hand, this is the revolution that EntityFramework has come
up with, Let’s give a round of applauseto our smartwork,
17. Time to write some code now:
Till now we have not written a single line of code, but to access th context class, weneed to change the logic from accessing
LINQ to SQL data context to EntityFramework data context in the controller wecreated earlier in second part of the tutorial.
Steps tofollow:
Step1: Bind all our views with UserListclass, later it was user class, butwe changed that to UserListclass (remember????)
Step2:Open the controllers, change the access mechanismof context class as shown below for e.g. IndexAction,
Earlier:
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:
18. 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 justhad to change access mechanism, mere change of 2-3 lines, and not anything in the logic of application.
Step3: Like wisedo the samefor all the Actions. I am not showing how to do here, but you can comparethe sourcecodes and
now can do by yourself.
Step4: 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.
Step5: All set now, rebuild your application, and you’ll not get a single error.Now ready to run.
Step6: When you run the application, it runs as was running previously and now you can performCRUP operations as an end
user to the application, and test the application .
19. Noth
Nothing more dude, we are done with Entity framework’sdatabasefirstapproach now.You can applauseagain, and take some
rest.
Conclusion:
We have already moved to one step on advanced level of CRUD operations in MVC.There is more to learn in MVCand Entity
Framework, thatwe’ll be covering in upcoming articles.In this article we mastered how to performCRUD operations in MVC
application using EntityFramework’sdatabasefirstapproach,nextarticle will focus on my favouriteCodeFirstapproach .
Happy Coding.