Sie sind auf Seite 1von 15

csharppulse .blo gspo t .

in

http://csharppulse.blo gspo t.in/2013/08/learning-mvc-part-3-creating-mvc.html

Learning MVC-Part 3 : Creating MVC Application & Perform CRUD Operations Using EntityFramework
Download Complete Source Code Introduction: In our f irst and second attempt to learn MVC, we learnt, what is MVC?, what is separation of concerns?, how to create a simple MVC application and perf orm CRUD operations on the application using LINQ to SQL. My this article f ocuses on how to perf orm CRUD operations in MVC application by the use of an ORM(Entity Framework). T he article is an attempt to overcome the conf usion related to how to use EntityFramework with MVC application in a very simple way. Our Roadmap: Our roadmap remains same,

1. Part1: Introduction to MVCarchitecture and Separation of Concerns. 2. Part 2: Creating MVC Application f romscratch and connecting it with database using LINQ to SQL. 3. Part 3: Connecting the MVC Application with the help of EntityFramework DB-First approach. 4. Part 4: Connecting the MVC Application with the help of EntityFramework Code-First approach. 5. Part 5: Implementing Repository Pattern in MVC Application with EntityFramework. 6. Part 6: Implementing a generic Repository Pattern and Unit Of Work pattern in MVC Application with EntityFramework.

Pre-requisites: T here are f ew pre-requisites bef ore we start with the article, We have running sample application that we created in second part of the article series. We have EntityFramework 4.1 package or dll on our local f ile system. We understand how MVC application is created.

What is ORM and EntityFramework?

T he topic isnt that scary as it seems to be. ORM(Object Relational Mapping) is basically an approach f or storing data f rom domain/entity objects to relational database in an automated way without writing much code. A true ORM is independent of what database server we ref er to, the code underlying ORMs is database independent and can run with any database server having similar database with a structure needed by the application.ORM has 3 main parts: Entity class objects, Relational db objects and inf ormation on how domain objects maps to relational db objects i.e. tables, views & storedprocedures. ORM helps us to keep our database design separate f rom our domain class design. T his makes our application maintainable and extendable. It also automates standard CRUD operation (Create, Read, Update & Delete) so developer doesnt require to code them manually J. Now lets have a look on standard def inition of Entity Framework given by Microsof t: 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 Frameworks ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their applicationspecific business logic rather than the data access fundamentals.

In a simple language, Entity f ramework is an Object/Relational Mapping (ORM) f ramework. It is an enhancement to ADO.NET, an upper layer to ADO.Net that gives developers an automated mechanism f or accessing & storing the data in the database. Hope this gives a glimpse of an ORM and EntityFramework. EntityFramework Architecture: Lets have a glance over the architecture of EntityFramework,

Our Web Application interacts with Entity Data Model (Entity Framework), that acts as an interf ace between ADO.Net Provider and database, f etches/saves data in the same f low as described in the f igure. Perform CRUD operations using EntityFramework on MVC application: Open the existing Learning MVC application that we created using LINQ to SQL,

I have made f ew changes in the existing application, just to make it easy to understand when we implement EntityFramework in it. 1.Changed t he model class name from User t o UserList ,

3. 6. 7. 8. 11. 13. 15. 17. 19. 22. .

namespace LearningMVC.Models 4. /// <summary>

{ 5.

#region User Model...

/// User Model Class, purposely used for populating views and carry data from database. /// </summary> 9. public class UserList 10. {

#region Aut omat ed Propert ies 12. public st ring First Name { get ; set ; } 14. public st ring EMail { get ; set ; } 16. public st ring PhoneNo { get ; set ; } 18. public st ring Designat ion { get ; set ; } 20. #endregion 23. }

public int UserId { get ; set ; } public st ring Last Name { get ; set ; } public st ring Address { get ; set ; } public st ring Company { get ; set ; } #endregion 21. }

2. Changed the Solution name f rom LearningMVC to LearningMVCWithEF.

Steps to Follow: 1. Open the application, modif y it by above given changes. 2. Delete the MyDBML.dbml class f rom the solution. 3. Do not build the solution now, it will result in an error, as we have removed the dbml f ile, so controller method accessing the dbml f ile will throw compile time errors. 4. Goto project right click and add new item, select Data in installed templates and add ADO.Nety EntityDataModel to the application,

Name it EFDataModel.edmx. 5.New window will be opened to choose model contents,

Since we are f ollowing Database First approach, select generate From Database. 6.Choose the connection and give the name to connection string as MVCEntities as shown in the f igure, click next.

7.Provide connection details to the existing database, that we used f or our existing application, database name was MVC. If you dont have existing one, create a new one with the attached db script f iles.

8. Choose data base objects, we have only one table , so choose that one as shown in f igure,

Give model namespace as MVCModel. 9.We get in our solution one guest,Entity Data Model that we saw in Entity Framework Architecture above,

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

11. Generating Strongly Typed Entity Model Classes:(taken f rom a blog) Well be working with the strongly typed entity classes now. T he Entity Data Model designer uses a code generator in Visual Studio called the Text Template Transf ormation Toolkit (T 4). Entity Framework will automatically generate a User class. T he code generator nowwill create a class based on our Entity Data Model. By def ault, the designer uses a template that results in entity classes that inherit f rom Entity Frameworks EntityObject and a container class which inherits f rom EFs ObjectContext. T hese base classes can be cumbersome to work with f or a number of reasons. While the ObjectContext is extremely usef ul when you need a lot of control over Entity Frameworks behavior, the lighter weight

DbContext provides access to the most commonly needed tasks and simplif ies your coding. Microsof t provides a number of alternative T 4 templates f or generating classes f rom the EDM. When you installed the EF 4.1, a template f or creating simpler classes including the DbContext was added to Visual Studio. Lets tell the designer to use this template instead of the def ault. Right click on the models designer surf ace. From the context menu, choose Add Code Generation Item. In the Add New Item dialog that opens, select Code f rom the list of installed templates types on the lef t. Choose the ADO.NET DbContext Generator then click the Add button.

Two new f iles will be listed in Solution Explorer, Model1.Context.tt and Model1.tt. T hese are template f iles. Expand the templates to see the generated classes as shown in f ollowing f igure,

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

Have you noticed that we havent written a single line of code by our hand, this is the revolution that EntityFramework has come up with, Lets give a round of applause to our smart work,

T ime to write some code now: Till now we have not written a single line of code, but to access th context class, we need to change the logic f rom accessing LINQ to SQL data context to EntityFramework data context in the controller we created earlier in second part of the tutorial. Steps to follow: Step1: Bind all our views with UserList class, later it was user class, but we changed that to UserList class (remember????) Step2:Open the controllers, change the access mechanism of context class as shown below f or e.g. Index

Action,

Earlier

public Act ionResult Index() { var dbCont ext = new MyDBDat aCont ext (); var userList = from user in dbCont ext .Users select user; var users = new List (); if (userList .Any()) { foreach (var user in userList ) { users.Add(new LearningMVC.Models.User() { UserId = user.UserId, Address = user.Address, Company = user.Company, First Name = user.First Name, Last Name = user.Last Name, Designat ion = user.Designat ion, EMail = user.EMail, PhoneNo = user.PhoneNo }); } } ViewBag.First Name = "My First Name"; ViewDat a["First Name"] = "My First Name"; if(TempDat a.Any()) { var t empDat a = TempDat a["TempDat a Name"]; } ret urn View(users); }

Now

public Act ionResult Index() { var dbCont ext = new MVCEnt it ies() ; var userList = from user in dbCont ext .Users select user; var users = new List (); if (userList .Any()) { foreach (var user in userList ) { users.Add(new LearningMVC.Models.UserList () { UserId = user.UserId, Address = user.Address, Company = user.Company, First Name = user.First Name, Last Name = user.Last Name, Designat ion = user.Designat ion, EMail = user.EMail, PhoneNo = user.PhoneNo }); } } ViewBag.First Name = "My First Name"; ViewDat a["First Name"] = "My First Name"; if(TempDat a.Any()) { var t empDat a = TempDat a["TempDat a Name"]; } ret urn 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. Step3: Like wise do the same f or all the Actions. I am not showing how to do here, but you can compare the source codes and now can do by yourself . Step4: Note LINQ to SQL context class uses InsertOnSubmit()/DeleteOnSubmit() and SubmitChanges() method f or Insert, update,Delete but EF context class uses .Add(), .SaveChanges().So do it skillf ully when required. Step5: All set now, rebuild your application, and youll 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 perf orm CRUP operations as an end user to the application, and test the application .

Nothing more dude, we are done with Entity f rameworks database f irst approach now.You can applause again, and take some rest.

Conclusion: We have already moved to one step on advanced level of CRUD operations in MVC.T here is more to learn in MVC and Entity Framework, that well be covering in upcoming articles.In this article we mastered how to perf orm CRUD operations in MVC application using EntityFrameworks database f irst approach,next article

will f ocus on my f avourite CodeFirst approach J. Happy Coding.

Das könnte Ihnen auch gefallen