Reputation: 33
I need advice on using stored procedures with Entity Framwork 4.x to return data into POCO objects. I don't want to have to copy the data from an entity object to a POCO object. I want to execute a stored proc and have the data loaded directly into my POCO class.
Is there a way to do this? Do I need some sort of mapping like you would use in Nhibernate? If so, could this mapping be attribute based?
Edit: Using Justin's help below, I found that the way to do this is:
SqlParameter p1 = new SqlParameter("@p1", "xxxx");
SqlParameter p2 = new SqlParameter("@p2", "yyyy");
SqlParameter[] parameters = new SqlParameter[2];
parameters[0] = p1;
parameters[1] = p2;
returned = base.ExecuteStoreQuery<YourClass>("exec your_stored_proc_name @p1, @p2", parameters);
Upvotes: 3
Views: 6226
Reputation: 67065
Yes, you can use the generic version of ExecuteStoreQuery once you get to the ObjectContext:
var listOfType= ((IObjectContextAdapter)context).ObjectContext
.ExecuteStoreQuery<Type>("SPROCNAME");
Here is the MSDN sample code (just change the TSQL to a sproc)
And, here is one that shows how to deal with parameters
The newer versions of EF has SqlQuery and DbContext.Database to get the ObjectContext easier:
var listOfType = context.Database.SqlQuery<Type>("SPROCNAME");
Upvotes: 4