是否可以在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表达式包含对与不同上下文关联的查询的引用。
答案 0 :(得分:0)
我将假设您已跳过涉及订单表的Where子句(否则连接将毫无意义)
在这种情况下,您可以让Linq推断加入。
var q = from c in customers
where c.Orders.Any(o=> o.ProductCode == productCode)
select c;
如果您定义了外键,Linq2Sql将自动创建Orders属性;我相信实体框架,你必须手动指定它。
答案 1 :(得分:0)
错误表示另一个问题:
如果您使用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()
}
答案 2 :(得分:0)
在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;