Friday, February 19, 2010

Entity Framework Stored Procedure mapping


Introduction



Now days, Microsoft have changed lots of thing in accessing database from .Net application. Microsoft has introduced Entity Framework to access database from the application. Entity framework is just a small wizard which helps to create classes to access the database. To know basic of Entity Framework please click on here.

In Part 1, I explained you how to create entity framework class in your project and how to insert, update or delete the record. Now in part 2, I explain you how to map your stored procedure with insert, update and delete functionality.

If you will not map your stored procedure then Entity Framework will create concrete SQL statement for insert, update and delete. If you will map your stored procedure then Entity Framework will execute your stored procedure with parameter value.

Let take an example of contact table which I explained schema in part 1.

After creating entity framework file (.edmx), Select “Contact” entity and open “Mapping Details” window. In Mapping Details window, click on “Map Entity to Function” button on left side. Refer below screen shot:




In Insert/Update/Delete function, Select your stored procedure and map your parameter value. Refer image below:



Now you have to just add/update/remove data using Entity Framework and It will execute your mapped stored procedure.

Following code is used to add new record into Contact table. When user will execute the code below, Entity Framework will execute “SPE_ContactInsert” stored procedure to insert contact information.

TestEntityEntities testEntityEntities = new TestEntityEntities();
Contact contact = new Contact();
contact.FirstName = "test1";
contact.LastName = "test2";
contact.Title = "Mr.";
testEntityEntities.AddToContact(contact);
testEntityEntities.SaveChanges();

As the same way you can update or delete the record. For more information please refer Entity Framework part 1 here.

No comments:

Post a Comment

DotNet Code Guru