Entity Framework Stored Procedures and POCO

99封情书 提交于 2019-11-30 18:06:13

问题


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);

回答1:


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");


来源:https://stackoverflow.com/questions/9930408/entity-framework-stored-procedures-and-poco

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!