Entity Framework:ObjectContext.ExecuteStoreQuery生成分离的对象

8

我需要运行一些自定义的SQL语句,从一个表中返回对象列表。为此我使用ExecuteStoreQuery。

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

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

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

2个回答

3

我自己解决了这个问题 - 你需要使用ExecuteStoreQuery重载方法,该方法允许你指定返回实体的EntitySet名称。


11
请您能否提供一个示例来说明解决方案? - user287745

2

由于似乎还没有一个带有代码的被接受的答案...

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

ExecuteStoreQuery<..>(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参数决定了框架在返回的实体已经存在于上下文中时的操作方式,即覆盖它们或使用现有对象(默认值)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接