实体框架存储过程和POCO [英] Entity Framework Stored Procedures and POCO

查看:209
本文介绍了实体框架存储过程和POCO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用存储过程与实体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的仿制版本一旦<一个href="http://social.msdn.microsoft.com/Forums/en/adonetefx/thread/0c1f8425-55f4-4600-9605-a925220d5a25"相对=nofollow>到达ObjectContext的:

  VAR listOfType =((IObjectContextAdapter)上下文).ObjectContext
                    .ExecuteStoreQuery&LT;类型&GT;(SPROCNAME);
 

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

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

较新版本的EF有使用SqlQuery 和<一href="http://msdn.microsoft.com/en-us/library/system.data.entity.dbcontext.database%28v=vs.103%29.aspx"相对=nofollow> DbContext.Database得到的ObjectContext容易:

  VAR listOfType = context.Database.SqlQuery&LT;类型&GT;(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");

这篇关于实体框架存储过程和POCO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆