LINQ Conditional Composite key in INNER JOIN

时间:2015-10-29 15:44:34

标签: c# linq join linq-to-entities inner-join

Let's say I have an Order and OrderDetails collections. How can I write following sql in LINQ (query or fluent syntax)?

select top 1 OD.ProductId
from Order O
inner join OrderDetail OD on OD.OrderID = 1
and OD.OrderId = O.OrderId
and ((OD.OrderDate = O.OrderDate) or (OD.OrderDate is null))
where O.CustomerId = 2
order by OD.OrderDate desc

I know that I can create an anonymous type containing all the columns to match for join however how can I write conditional logic for inner join as mentioned above in BOLD

1 个答案:

答案 0 :(得分:3)

您的查询结果如下:

select top 1 OD.ProductId
from Order O
inner join OrderDetail OD
  on OD.OrderId = O.OrderId
where O.CustomerId = 2
  and OD.OrderID=1
  and (OD.OrderDate is null or OD.OrderDate=O.OrderDate)
order by OD.OrderDate desc

您应该能够更轻松地将其转换为LINQ。

var results=db.OrderDetail
  .Where(od=>od.Order.CustomerId==2)
  .Where(od=>od.OrderId==1)
  .Where(od=>od.OrderDate==null || od.OrderDate==od.Order.OrderDate)
  .OrderBy(od=>od.OrderDate)
  .Select(od=>od.ProductId)
  .First();

您可以进一步简化为:

var results=db.OrderDetail
  .Where(od=>od.Order.CustomerId==2 &&
    (od.OrderId==1) &&
    (od.OrderDate==null || od.OrderDate==od.Order.OrderDate))
  .OrderBy(od=>od.OrderDate)
  .Select(od=>od.ProductId)
  .First();