【问题标题】:LINQ Equivalent of and SQL query with two inner joins and a left joinLINQ 等价于和带有两个内连接和一个左连接的 SQL 查询
【发布时间】:2015-07-26 11:25:43
【问题描述】:

我将不胜感激有关以下 SQL 查询(有效)的 LINQ 等效项的帮助。在这个 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。订单表中的这两个外键对应每个订单可以拥有的两个产品。客户表有一个来自订单表的外键。

现在我需要 LINQ 查询方面的帮助,该查询将返回所有客户,以便我获得五个字段 - CustomerName、OrderID 和与客户产品中的 OrderID 匹配的两种产品中的每一种的名称。

【问题讨论】:

  • 请显示一个类模型,以便导航属性和关联的多样性可见。此外,请说明您的目标是什么类型的 LINQ(针对实体?),展示您自己的初步努力。他们向我们解释的内容比您想象的要多。

标签: linq join


【解决方案1】:

您的链接不存在,所以这是一个最好的尝试,没有看到任何东西。

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

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 .

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 2012-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多