LINQ与两个内连接和左连接的SQL查询的等价和

时间:2015-07-26 11:25:44

标签: linq join

我将非常感谢LINQ等效的以下SQL查询(可行)。在这个SQL查询下面,我给出了我的简单数据库和我想要解决的问题的一些描述。

 Select a.Name, a.OrderID, 
 b.ProductIDFirst, c1.productName ProductNameFirst, 
 b.ProductIDSecond , c2.productName ProductNameSecond
 from Customers a
 INNER JOIN ORDERS b ON a.OrderID = b.OrderID
 left join products c1 on b.productidfirst = c1.productid
 left join products c2 on b.ProductIDSecond = c2.productid

有关数据库结构的背景信息: 我有一个简单的SQL Server数据库,有三个名为Products,Orders和Customers的表。   商业模式是每个订单只能有两个产品(而不是更多)。   Orders表有两个外键,但它们都来自Products表。订单表中的这些外键字段名称是ProductIDFirst和ProductIDSecond。订单表中的这两个外键对应于每个订单可以具有的两个产品。 Customers表有一个来自Orders表的外键。

现在我需要一个LINQ查询的帮助,它将返回给我所有客户,这样我就得到五个字段 - CustomerName,OrderID和两个产品中每个与客户产品中的OrderID匹配的名称。

1 个答案:

答案 0 :(得分:0)

您的链接不存在,所以这是最好的尝试而没有看到任何内容。

假设您有以下容器(您需要根据您的方案更改它们):

var customers = new List<Customer>();
var orders = new List<Order>();
var products = new List<Product>();

您可以执行以下操作:

var query =
from a in customers
join b in orders
on a.OrderId equals b.OrderId
join c1 in products
on b.ProductIdFirst equals c1.ProductId into c1a
join c2 in products
on b.ProductIdSecond equals c2.ProductId into c2a
from p1 in c1a.DefaultIfEmpty()
from p2 in c2a.DefaultIfEmpty()
select new
{
Name = a.Name,
OrderId = a.OrderId,
ProductIdFirst = p1 == null ? null : p1.ProductIdFirst,
ProductNameFirst = p1 == null ? null : p1.ProductNameFirst,
ProductIdSecond = p2 == null ? null : p1.ProductIdSecond,
ProductNameSecond = p2 == null ? null : p1.ProductNameSecond,
};

简而言之,在你想要左连接的地方,将连接投射到其他东西(例如c1a,c2a)然后使用DefaultIfEmpty()从它们调用,当右侧没有匹配的项目时将设置为null