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

时间:2016-10-08 01:22:34

标签: c# sql-server linq join lambda

我现在已经在这个问题上敲了两天左右。

我有一个非常高级的SQL Server查询,我需要将其转换为LINQ。

涉及:

  • 6个内连接
  • 包含每个表的列的选择
  • 一个特定的groupby,涉及每个表中的大量列。

我还需要能够动态构建where子句谓词(使用谓词构建器),所以如果我想在正确的位置应用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

非常感谢你的时间(提前)!

2 个答案:

答案 0 :(得分:2)

以下是您预期的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。

在这种情况下,我们将投射每个连接的结果并前进完整的对象而不是几个属性

答案 1 :(得分:0)

Mrinal Kamboj answer已经显示了如何将示例查询语法转换为方法语法。但是,这并不是绝对必要的,因为您可以通过简单地在末尾添加匿名类型投影来实现相同的目标,然后执行其余的操作(动态过滤,最终投影):

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