How to handle stored procedure that returns different outputs in Entity Framwork. For example , on sp, there is if condition and else condition. if condition return integer and else condition return datatable. How to handle this using entity framework in vs. Please advice.
-
possible duplicate of [Entity Framework - stored procedure return value](http://stackoverflow.com/questions/10339750/entity-framework-stored-procedure-return-value) – Ed Chapel Jun 18 '13 at 08:46
-
possible duplicate of [Stored procedures in entity framework](http://stackoverflow.com/questions/1506193/stored-procedures-in-entity-framework) – gbjbaanb Jun 18 '13 at 08:49
-
Yes, This is not possible in ef right now.I tried a lot. – Raju S Nair Jun 18 '13 at 12:14
4 Answers
Starting from EF 4.1 this is possible. The only requirement is to know what the SP is going to return in each case.
In my example I use
DbContext.Database.SqlQuery<TElement>(string sql, params object[] parameters)
This generic method takes as a generic parameter the type you would like to use for materialization. It also takes SQL expression you would like to execute as a parameter, along with it's parameters as param'd array.
Simplified SP (no input parameters) usage is:
var res = ctx.Database.SqlQuery<MyResultType1>("dbo.MyStoredProcedure");
foreach (var r in res)
{
System.Console.Out.WriteLine(
"col1:{0}; col2:{1}; col3={2}",
r.Col1,
r.Col2,
r.Col3);
}
So, you can do following:
IEnumerable res
if(...your logic...)
{
res = ctx.Database.SqlQuery<MyResultType1>(...your SP call...);
}
else
{
res = ctx.Database.SqlQuery<MyResultType2>(...your SP call...);
}
This way you are going to fill your collection with SP output resultset the way you want.

- 5,535
- 4
- 34
- 57
Click update model from database select your stored procedure and make sure it procedure has been added in Function Imports(Model Browser)
You can change return values from Edit function import window
and then just execute db.myProcedure();

- 33,492
- 33
- 111
- 169
eg: just drag and drop your stored procedure and then
db.procedure(element1, element2);
db.SubmitChanges();

- 515
- 3
- 15
Ef4 does not support stored procedure with multiple returns of different types. We can do it either by direct calling of Sp via sql codes or can do the schema in linq.
Else we needs to use EF 4.1 and above.

- 333
- 2
- 5
- 17