Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Stored Procedures and POCO

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);
like image 443
Silent-Cartographer Avatar asked Jul 11 '26 16:07

Silent-Cartographer


1 Answers

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");
like image 144
Justin Pihony Avatar answered Jul 14 '26 06:07

Justin Pihony



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!