【问题标题】:Correct syntax for multiple left joins in LINQ?LINQ中多个左连接的正确语法?
【发布时间】:2014-06-30 21:25:51
【问题描述】:

我正在尝试找出多个左连接的 LINQ 语法,但出现错误:The name 'c' is not in scope on the left side of 'equals'. Consider swapping the expressions on either side of 'equals'.

我已经尝试过交换,如果我这样做了,它会使 'c' 和 'd' 都出现“不在范围内”错误。

            var result = 
                    from a in db.tableA

                    join b in db.tableB //first join (inner join)
                        on a.field1 equals b.field1

                    join c in db.tableC //second join (left join)
                        on a.field1 equals c.field1
                            into left_one

                    join d in db.tableD   //third join (left join)
                        on c.field2 equals d.field2
                        // ^ here
                            into left_two


                    where a.field1 == theValueImSearchingFor


                    from c in left_one.DefaultIfEmpty()
                    from d in left_two.DefaultIfEmpty()

                    select new CombinedObject()
                    {
                        ...
                    }

我在第三个连接语句中使用on c.field2 equals d.field2 的原因是我的表结构如下:

tableA:   field1
tableB:   field1
tableC:   field1    field2
tableD:             field2

也就是说,将 tableD 与其余数据相关联的唯一方法是使用field2

有人可以纠正我的语法吗?或者考虑到我的表格设置,我必须采取某种方式吗?

【问题讨论】:

    标签: c# linq entity-framework join left-join


    【解决方案1】:

    我使用这种语法:

    var results = (from a in db.tableA
      from b in db.tableB.Where(s => s.field1 == a.field1)
      from c in db.tableC.Where(s => s.field1 == a.field1).DefaultIfEmpty()
      from d in db.tableD.Where(s => s.field2 == c.field2).DefaultIfEmpty()
      select new CombinedObject() { });
    

    它似乎在多个表上运行良好。我想我的 field1s 和 field2s 与您的示例相匹配:)

    [编辑]

    根据评论,如果您想添加一些额外的过滤,只需将其添加到Where() 的适当位置即可。例如:

      from c in db.tableC.Where(s => s.field1 == a.field1 && s.field3 == someVariable).DefaultIfEmpty()
    

    类似的东西:)

    【讨论】:

    • 我可以在哪里搜索 field1 的特定值?例如,我试图搜索where a.field1 == theValueImSearchingFor。我会把它放在select 声明之前吗?
    • 将其添加到相应的.Where() 中。我为这个示例提取的代码正是这样 :) 我将在第二种情况下编辑我的答案。
    • 它起作用了,并且 lambda 表达式使它更清晰。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多