【发布时间】:2009-07-08 03:20:26
【问题描述】:
关于 SO 已经有很多关于 Linq 中的左连接的问题,而我看过的所有问题都使用 join 关键字来达到预期的目的。
这对我来说没有意义。假设我有表Customer 和Invoice,通过Invoice 上的外键CustomerID 链接。现在我想运行一个包含客户信息以及任何发票的报告。 SQL 将是:
select c.*, i.*
from Customer c
left join Invoice i on c.ID = i.CustomerID
从我看到的关于 SO 的答案来看,人们大多建议:
var q = from c in Customers
join i in Invoices.DefaultIfEmpty() on c.ID equals i.CustomerID
select new { c, i };
我真的不明白这怎么可能是唯一的方法。 Customer 和 Invoice 之间的关系已经由 LinqToSQL 类定义;为什么我必须为join 子句重复它?如果我想要一个内部连接,那就是:
var q = from c in Customers
from i in c.Invoices
select new { c, i };
不指定连接的字段!
我试过了:
var q = from c in Customers
from i in c.Invoices.DefaultIfEmpty()
select new { c, i };
但这只是给了我与内部连接相同的结果。
没有更好的方法吗?
【问题讨论】:
标签: c# linq linq-to-sql