实体框架存储过程和POCO存储过程、实体、框架、POCO

由网友(Despair(绝望))分享简介:我需要使用存储过程与实体Framwork 4.x到的数据返回到POCO对象的意见。我不希望有将数据从一个实体对象复制到POCO对象。我想执行一个存储过程,并直接加载到我的POCO类中的数据。有没有办法做到这一点?我是否需要某种形式的映射,就像您在NHibernate中使用?如果是这样,可以此映射可以基于属性的?编辑:用...

我需要使用存储过程与实体Framwork 4.x到的数据返回到POCO对象的意见。我不希望有将数据从一个实体对象复制到POCO对象。我想执行一个存储过程,并直接加载到我的POCO类中的数据。

有没有办法做到这一点?我是否需要某种形式的映射,就像您在NHibernate中使用?如果是这样,可以此映射可以基于属性的?

编辑:用Justin的帮助下,我发现,要做到这一点的方法是:

 的SqlParameter P1 =新的SqlParameter(@ P1,XXXX);
的SqlParameter P2 =新的SqlParameter(@ P2,YYYY);

的SqlParameter []参数=新的SqlParameter [2];
参数[0] = P1;
参数[1] = P2;

返回= base.ExecuteStoreQuery< YourClass>(EXEC your_stored_proc_name @ P1,P2 @,参数);
 

解决方案

是的,你可以使用的 ExecuteStoreQuery的仿制版本一旦到达ObjectContext的:

  VAR listOfType =((IObjectContextAdapter)上下文).ObjectContext
                    .ExecuteStoreQuery<类型>(SPROCNAME);
 

这里是MSDN示例code(只是改变TSQL到存储过程)

LINQ TO SQL 介绍 定义数据模型类 – Part.2

而且,这里是一个展示如何处理参数

较新版本的EF有使用SqlQuery 和 DbContext.Database得到的ObjectContext容易:

  VAR listOfType = context.Database.SqlQuery<类型>(SPROCNAME);
 

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

解决方案

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

阅读全文

相关推荐

最新文章