实体框架:ObjectContext.ExecuteStoreQuery生成分离的对象

时间:2010-02-04 16:37:43

标签: c# .net entity-framework

我需要运行一些自定义SQL来返回表中的对象列表。我正在使用ExecuteStoreQuery。

var q = context.ExecuteStoreQuery<ProductionUnit>(MySelectString, new SqlParameter("@ProductionUnitId", value));

这会导致q包含ObjectResult集合,但实际的ProductionUnit元素是Detached,并且它们的EntityKey为null。在尝试处理其中某些对象或其关系时,这会产生许多问题。我的SQL查询返回一个结果集,其中包含相应ProductionUnits表的所有列(仅此而已)。

我需要做的其他事情才能跟踪这些对象,还是设计出这种行为?

3 个答案:

答案 0 :(得分:3)

我自己解决了 - 您需要使用ExecuteStoreQuery重载,它允许您为返回的实体指定EntitySet名称。

答案 1 :(得分:1)

因为似乎没有接受代码的答案......

正如@neaorin所说,为了确保跟踪对返回实体的更改,请使用方法

  

ExecuteStoreQuery&lt; ..&gt;(commandText,entitySetName,MergeOptions,args   PARAMATERS)

如下:

string strQuery = "SELECT * FROM employees WHERE id=999";
List<employee> employees;
services = context.ExecuteStoreQuery<employee>(strQuery, "employees", System.Data.Objects.MergeOption.AppendOnly).ToList();

MergeOptions参数指示如果其中一些返回的实体已经在上下文中浮动,那么框架会执行什么操作,即是否覆盖它们或使用现有对象(默认值)。

答案 2 :(得分:0)

在我的情况下,解决方案是将重载与 EntitySet 字符串和 MergeOption 一起使用,如先前答案中所述。 但是,ExecuteStoreQuery仍返回EntityKey = null且EntityState = Detached的实体项目。

原因是我使用的EntitySet字符串错误,我通过使用以下命令获得了正确的EntitySet字符串:

var records = _entities.ExecuteStoreQuery<ProductionUnit>(query, typeof(ProductionUnit).Name, System.Data.Entity.Core.Objects.MergeOption.AppendOnly).ToList();

我使用typeof(ProductionUnit).Name得到了正确的EntitySet字符串。