Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
具有两个内部联接和一个左联接的与SQL查询的LINQ等价的_Linq_Join - Fatal编程技术网

具有两个内部联接和一个左联接的与SQL查询的LINQ等价的

具有两个内部联接和一个左联接的与SQL查询的LINQ等价的,linq,join,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

我将非常感谢您对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表。Orders表中的这些外键字段名是ProductIDFirst和ProductIDSecond。orders表中的这两个外键对应于每个订单可以拥有的两个产品。Customers表有一个来自Orders表的外键


现在,我需要一个LINQ查询的帮助,该查询将返回我所有的客户,这样我就可以得到五个字段——CustomerName、OrderID以及与客户产品中的OrderID相匹配的两个产品的名称

您的链接不存在,因此这里有一个最好的尝试,您可以不看到任何内容

假设您有以下容器(您需要为您的场景更改它们):


简言之,在需要左连接的地方,将连接投影到其他对象(例如c1a、c2a),然后使用DefaultIfEmpty()从中调用,当右侧不存在匹配项时,该函数将设置为null。

请显示类模型,以便导航属性和多个关联可见。另外,告诉你的目标是什么类型的LINQ(对实体?),并展示你自己的第一次努力。他们向我们澄清的比你想象的要多。
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,
};