Legacy Support with Entity Framework–Stored Procs

8. April 2011

I have gotten several questions over the last few months over how to leverage Entity Framework with a large number of legacy stored procedures that cannot be re-written whole sale. The answer is slowly convert your data access to Entity framework using function imports, and as time permits move that logic into the query repository so that it can be unit tested and consistent.

Here is how to do it.

Make sure that you have added the stored procedures to the model.

image

Then right click the white background on the canvas…

image

This brings up the wizard…

image

1. Chose a Stored Procedure

2. Name the Method you will call in code for this.

3. Click the radio button for the complex type.

4. Click get column information.

5. Click Create New Complex Type – This saves a lot of manual creation.

6. Name your complex object.

7. Click Ok.

After these quick and easy steps you can then use this by calling the method on the entities.

image

Notice the Type safe parameters – This will help you avoid run time type mismatch issues throwing SQL Exceptions.

ObjectResult<BillOfMaterials> billOfMaterials = entities.GetBillOfMaterials()
billOfMaterials.Select(x => x.StandardCost);

You can then call against this just like any other collection of objects.

 

Enjoy

Entity Framework, Productivity , ,