【问题标题】:Entity Framework - Left outer join on multiple columns with OR condition实体框架 - 具有 OR 条件的多个列的左外连接
【发布时间】:2020-03-25 08:45:56
【问题描述】:

是否可以在多个列上编写 lambda left join 来生成 OR 条件而不是 AND?

var query = context.table1.GroupJoin(
    context.table2,
    x => new { JoinCol1 = x.CustomerCode, JoinCol2 = x.CustomerName},
    y => new { JoinCol1 = y.Code, JoinCol2 = y.Name},
    (x, y) => new { 
        firstTable = x,
        secondTable = y
    }).SelectMany(
       x => x.OrganizationAddress.DefaultIfEmpty(),
       (x, y) => {
          x.firstTable.field1,
          x.firstTable.field2,
          y.Field3,
          y.Field4
       }
    )

这将生成以下查询

    SELECT t1.filed1, t1.field2, t2.field3, t2.field4 
    FROM table1
    LEFT JOIN table2 ON table1.CustomerCode = table2.Code 
                     AND table1.CustomerName = table2.Name 

我想获得相同的查询,但我希望它是 OR,而不是 AND 条件:

    SELECT t1.filed1, t1.field2, t2.field3, t2.field4 
    FROM table1
    LEFT JOIN table2 ON table1.CustomerCode = table2.Code 
                     OR table1.CustomerName = table2.Name 

有没有办法做到这一点?

编辑:版本 - EF 6.2.0

【问题讨论】:

  • EF6 还是 EF Core?版本?
  • @IvanStoev EF 6.2.0,我会将此信息添加到问题中。

标签: c# sql entity-framework


【解决方案1】:

LINQ 连接运算符(JoinGroupJoin)仅支持等值连接。所有其他连接类型都必须作为相关子查询来实现。

对于有问题的连接,您只需使用替代的 LINQ 左外连接 模式 - 将 SelectManyDefaultIfEmpty() 相关联。像这样的:

var query = context.table1.SelectMany(
    t1 => context.table2
        .Where(t2 => t1.CustomerCode == t2.Code || t1.CustomerName == t2.Name)
        .DefaultIfEmpty(),
    (t1, t2) => new
    { 
        t1.field1,
        t1.field2,
        t2.Field3,
        t3.Field4
    });

【讨论】:

  • 谢谢!这正是我想要的。
猜你喜欢
  • 2018-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
  • 2012-01-08
  • 1970-01-01
  • 1970-01-01
  • 2022-07-29
  • 1970-01-01
相关资源
最近更新 更多