LINQ join lambda语法-需要从查询中翻译出来

本文关键字:查询 翻译 lambda join 语法 LINQ | 更新日期: 2023-09-27 18:12:10

我已经为这件事绞尽脑汁两天了。

我有一个非常先进的SQL Server查询,我需要翻译成LINQ。

它涉及:

  • 6个内连接
  • 包含来自每个表的列的选择
  • 涉及每个表的大量列的特定组。

我还需要能够动态地构建一个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 join lambda语法-需要从查询中翻译出来

以下是您的查询的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的Final Result/Schema是由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);
...