[英]LINQ join lambda syntax - need to translate this from query
我已經為此努力了大約2天。
我有一個非常高級的SQL Server查詢,需要將其轉換為LINQ。
它涉及:
我還需要能夠動態構建一個where子句謂詞(使用predicatebuilder),因此,如果我希望將where子句應用於正確的位置,我想我需要使用lambda表達式(經過多次試驗和錯誤)。
這是我很難翻譯的部分:
var query = from order in orders
join customer in customers on order.CustomerID equals customer.ID
join ordersection in ordersections on order.ID equals ordersection.OrderID
join ticket in tickets on ordersection.ID equals ticket.OrderSectionID
join evt in events on ticket.EventID equals evt.id
join client in clients on evt.ClientID equals client.id
join venue in venues on evt.VenueID equals venue.VenueID
非常感謝您的時間(提前)!
以下是查詢的Linq
版本:
var query = orders.Join(customers, o => o.CustomerID, c => c.ID, (o, c) => new { o, c })
.Join(ordersections, o => o.o.ID, os => os.OrderID, (o, os) => new {o = o.o, c = o.c,os})
.Join(tickets, o => o.os.ID, t => t.OrderSectionID, (o, t) => new {o = o.o, c = o.c,os = o.os,t})
.Join(events, o => o.t.EventID, e => e.id, (o, e) => new {o = o.o, c = o.c,os = o.os,t = o.t,e})
.Join(clients, o => o.e.ClientID, cl => cl.id, (o, cl) => new {o = o.o, c = o.c,os = o.os,t = o.t,e = o.e,cl})
.Join(venues, o => o.e.VenueID, v => v.VenueID, (o, v) => new {o = o.o, c = o.c,os = o.os,t = o.t,e = o.e,cl = o.cl,v});
最終query
結果/模式是由order,customer,ordersection,ticket,evt,client,venue
組成的匿名類型,您可能希望將其轉換為類型化的實體/ DTO。
在這種情況下,我們將投影每個聯接的結果,並采用完整的對象而不是幾個屬性
Mrinal Kamboj的答案已經顯示了如何將示例查詢語法轉換為方法語法。 但是,這並不是絕對必要的,因為您可以通過在末尾簡單地添加匿名類型投影,然后在其上執行其余操作(動態過濾,最終投影)來實現相同目的:
var query =
from order in orders
join customer in customers on order.CustomerID equals customer.ID
join ordersection in ordersections on order.ID equals ordersection.OrderID
join ticket in tickets on ordersection.ID equals ticket.OrderSectionID
join evt in events on ticket.EventID equals evt.id
join client in clients on evt.ClientID equals client.id
join venue in venues on evt.VenueID equals venue.VenueID
select new { order, customer, ordersection, ticket, evt, client, venue };
query = query.Where(dynamicFilter);
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.