Entity Framework - CRUD using Stored Procedure


Use of stored procedures for CUD (create, update, delete) operation using DbContext. Context class executes stored procedures instead of DDL statements on context.SaveChanges().

We are going to use following stored procedures:-
1. DU_FND_Message_INSERT
2. DU_FND_Message_UPDATE
3. DU_FND_Message_DELETE

1. Add all the three stored procedures into EDM. Import selected stored procedures and function into the entity model checkbox is checked.

Use of stored procedures for CUD (create, update, delete)

2. On clicking Finish button, Model Browser will add procedures into storage model but not in Function Imports.

EntityFramework: Use of stored procedures for CUD (create, update, delete)

3. In the EDM designer, right click on DU_FND_Message entity and select Stored Procedure Mapping to open Mapping details.

EntityFramework:Use of stored procedures for CUD (create, update, delete)

4. In the Mapping Details, there are 
    A) <Select Insert Function>, 
    B) <Select Update Function>, and 
    C) <Select Delete Function>. 
Select the related stored procedure for each one and complete the mapping of Insert, Update and Delete procedures:-

EntityFramework:Use of stored procedures for CUD (create, update, delete)

5. We have to validate it before executing to ensure that there will not be a run time error. To accomplish this, right click on DU_FND_Message entity in the designer and click Validate and make sure that there are no warnings or errors:

EntityFramework:Use of stored procedures for CUD (create, update, delete)

Now you can add, update, or delete messages using 

using (var context = new DemoDBEntities())
{
   //Add new message
    DU_FND_Message newMsg = new DU_FND_Message() {ToID = 5,FromID = 6, Message = "New Message",Subject="Message Subject"};
    context.DU_FND_Message.Add(newMsg);
    context.SaveChanges();

    //Update Message
    newMsg.User_MessageID=9;
    newMsg.Message = "Updated Message";
    newMsg.Subject="Updated Subject";
    context.SaveChanges();

    //Remove Message
    newMsg.User_MessageID=9;
    context.DU_FND_Message.Remove(newMsg);
    context.SaveChanges();
}


 

Praesent mattis

Pellentesque viverra vulputate enim. Aliquam erat volutpat. Pellentesque tristique ante ut risus. Quisque dictum. Integer nisl risus, sagittis convallis, rutrum id, elementum congue, nibh. Suspendisse dictum porta lectus. Donec placerat odio vel elit.

Read More