Entity Framework: getting sproc results the easy way

Most of the articles I read on EF are focused on projects where you only have a database, no sprocs, and your entity model is your primary method for manipulating that data…

In the world I work in, that’s typically not allowed for some good reasons.  Mostly because the database and sprocs/functions/etc have all been written, tested, and used for years and no one (i.e. your business user(s)) is going to want to do that again just because you want to upgrade technology.

So, while modeling data is fun and cool, I’m just going to show how to slap some Data Access Code around an Entity Framework model that was literally dropped on top of an existing database and then all the sprocs were imported and assigned function imports.  That’s about the easiest thing you can do to integrate EF with an existing database-designed application.

Say you have a grid and you want to bind it to the results of a sproc…  no problem:

In your DAL, it could look as simple as this:

public static System.Data.Objects.ObjectResult ef_GetSomeData(DateTime someDate)
{
 Your_Entity db = new Your_Entity();
 return db.sp_GetSomeData(someDate);
}

That’s great for a grid, but what about all the other scenarios?  What about getting it in an easy format for feeding single values to a bunch of form fields?  Personally, I just want it in the fewest lines possible so the next person to come along doesn’t want to strangle me.  Also, if you search on this, you’ll find a lot of very upset people trying their best to cram those results into a DataTable.  If that’s you, my advice is stop now ;-)

Here’s an easier way:

public static Your_Entity.sp_SomeData_Result sp_up_GetSomeData(DateTime someDate)
{
 Your_Entity db = new Your_Entity();
 System.Collections.IEnumerator enumerator = ((System.Collections.IEnumerable)db.sp_SomeData(someDate)).GetEnumerator();
 enumerator.MoveNext();
 Your_Entity.sp_SomeData_Result r = (Your_Entity.sp_SomeData_Result)enumerator.Current;
 return r;
}

 Then you can do it in one line on your test page:

Your_Entity.sp_SomeData_Result data = DAL.sp_up_GetSomeData(someDate);
//Assign it to some fields on the screen
SomeData1.Text = string.Format("{0:c2}",data.field1);
SomeData2.Text = string.Format("{0:c2}",data.field2);
SomeData3.Text = string.Format("{0:c2}",data.field3);

No muss, no fuss.

© Copyright Duke Hall - Designed by Pexeto