问题
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