我有来自AdventureWorks DB的以下查询
from customer in Customer
where customer.CustomerID == 20042
select new {
customer.AccountNumber,
Order = from order in customer.SalesOrderHeader
select new { order }
}
Customer表与SalesOrderHeader的关系为1:M。生成的T-SQL在SalesOrderHeader表上执行左外连接。有人可以告诉我为什么吗?而且,如果我想要内部连接,那该怎么办呢?我该如何更改此查询?
答案 0 :(得分:1)
即使它是一对多,你仍然必须允许它是一对一的。也就是说,客户可能没有订单。如果您不进行外部联接,如果此特定客户没有订单,您将完全没有记录。
答案 1 :(得分:1)
如果您想进行内部联接,请使用:
from customer in Customer
where customer.CustomerID == 20042
from order in customer.SalesOrderHeaders
select new { customer.AccountNumber, Order = order }
如果您只想过滤掉没有SalesOrderHeaders的客户,请使用以下命令:
from customer in Customer
where customer.CustomerID == 20042
where customer.SalesOrderHeaders.Any()
select new {
customer.AccountNumber,
Order =
from order in customer.SalesOrderHeaders
select order
}