【问题标题】:How do you Left join 'Is Not Null' using linq?您如何使用 linq 离开加入“非空”?
【发布时间】:2021-02-09 21:27:07
【问题描述】:

我在让我的 LINQ 语句正常工作时遇到了一些问题。我要加入一个表 secondTable,其中一个列可以为空,但我只需要该列不为空的记录。我不确定如何将以下内容放入 LINQ 表达式中

LEFT JOIN secondTable b ON a.ID = b.oneTableID AND b.name IS NOT NULL

到目前为止,我的 LINQ 是:

var list = await (from one in dbRepository.oneTable
                  join two in dbRepository.secondTable
                  on new { name = one.name, phone = one.phone, height = { is not null} } equals new 
                  { name = two.name, phone = two.phone, height = two.height 
                  into temp
                  from two in temp.DefaultIfEmpty()
                  select new.....

有什么想法吗?

编辑 1:我找到了解决方案。

 var list = await (from one in dbRepository.oneTable
                  join two in dbRepository.secondTable
                  on new { name = one.name, phone = one.phone, height = false } equals new 
                  { name = two.name, phone = two.phone, height = string.IsNullOrEmpty(two.height)}
                  into temp
                  from two in temp.DefaultIfEmpty()
                  select new.....

【问题讨论】:

    标签: c# sql-server linq


    【解决方案1】:

    您必须使用SelectMany 来创建 LEFT JOIN:

    var query = 
        from one in dbRepository.oneTable
        from two in dbRepository.secondTable
            .Where(two => two.name = one.name && two.phone == one.phone 
                && two.height != null)
            .DefaultIfEmpty()
        select new.....
    

    【讨论】:

      【解决方案2】:

      试试这个:

      var list = await (from one in dbRepository.oneTable
                        join two in dbRepository.secondTable
                        on new { name = one.name, phone = one.phone} 
                        equals new 
                        { name = two.name, phone = two.phone}
                        into temp
                        from two in temp.DefaultIfEmpty()
                        where one.height == null || one.height = two.height 
                        select new.....
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        相关资源
        最近更新 更多