【问题标题】:Join in linq: "The specified LINQ expression contains references to queries that are associated with different contexts."加入linq
【发布时间】:2009-03-24 20:40:41
【问题描述】:

是否可以在 linq 中进行连接,并且只从一个数据集中返回另一个键存在的数据,有点像:

 var q = from c in customers
            join o in orders on c.Key equals o.Key
            select new {c.Name, o.OrderNumber};

然后不是只返回两条记录,而是返回客户,例如:

  var q = from c in customers
                join o in orders on c.Key equals o.Key
                select c;

当我尝试做(类似的事情)时,我得到了这个错误: 指定的 LINQ 表达式包含对与不同上下文关联的查询的引用。

【问题讨论】:

  • 客户和订单是否在同一个数据上下文中?
  • 我同意斯蒂芬的观点,你是否使用相同的数据上下文,错误消息似乎非常具体。

标签: linq entity-framework


【解决方案1】:

我假设您已经跳过了涉及订单表的 Where 子句(否则连接将毫无意义)

在这种情况下,您可以让 Linq 推断连接。

var q = from c in customers
       where c.Orders.Any(o=> o.ProductCode == productCode)
       select c;

如果您定义了外键,Linq2Sql 将自动创建 Orders 属性;我相信使用实体框架,您必须手动指定它。

【讨论】:

  • 我敢说他没有跳过它。毕竟,第一个代码看起来是正确的。鉴于所描述的错误文本,我的假设是他正在尝试组合两个数据上下文
  • 我假设有一个 WHERE,因为没有它,该行可能会写成“var q = from c in customers select c;”
【解决方案2】:

该错误表明另一个问题:
如果您使用 Linq to SQL,则必须在查询中的每个对象上使用相同的 DataContext。

你的代码应该是这样的:

using (MyDataContext dc = new MyDataContext())
{
    var q = from c in dc.customers
            join o in dc.orders on c.Key equals o.Key
            select c;

    // process q within the DataContext
    // the easies would be to call q.ToList()
}

【讨论】:

    【解决方案3】:

    是否会在 EF 4.0 中从多个上下文创建连接?

    例如:

    TestModelEntities e1 = new TestModelEntities();
            TestModelEntities e2 = new TestModelEntities();
    
            var d = from firme1 in e1.firme
                    join g in e2.grad on firme1.grad.grad_id equals g.grad_id
                    select firme1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-09
      • 2011-07-21
      相关资源
      最近更新 更多