【问题标题】:Entity Framework: ObjectContext.ExecuteStoreQuery produces detached objects实体框架:ObjectContext.ExecuteStoreQuery 产生分离的对象
【发布时间】:2010-02-04 16:37:43
【问题描述】:

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

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

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

我还需要做什么才能跟踪这些对象,或者这种行为是设计使然吗?

【问题讨论】:

    标签: c# .net entity-framework


    【解决方案1】:

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

    【讨论】:

    • 能否提供一个示例解决方案
    【解决方案2】:

    由于似乎没有可接受的代码答案...

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

    ExecuteStoreQuery<..>(commandText, entitySetName, MergeOptions, args 参数)

    如下:

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

    MergeOptions 参数规定了如果其中一些返回的实体已经在上下文中浮动,框架会做什么,即是否覆盖它们或使用现有对象(默认)。

    【讨论】:

      猜你喜欢
      • 2012-03-27
      • 1970-01-01
      • 2016-12-19
      • 1970-01-01
      • 1970-01-01
      • 2010-09-28
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      相关资源
      最近更新 更多