LINQ Conditional Composite key in INNER JOIN

时光怂恿深爱的人放手 提交于 2019-12-11 12:21:58

问题


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:


Your query will give the same results as:

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

You should be able to convert that to LINQ much easier.

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();

You can further simplify that to:

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();


来源:https://stackoverflow.com/questions/33418771/linq-conditional-composite-key-in-inner-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!