【问题标题】:LINQ to SQL - Left Outer Join with multiple join conditionsLINQ to SQL - 具有多个连接条件的左外连接
【发布时间】:2010-11-10 12:16:52
【问题描述】:

我有以下 SQL,我正在尝试将其转换为 LINQ:

SELECT f.value
FROM period as p 
LEFT OUTER JOIN facts AS f ON p.id = f.periodid AND f.otherid = 17
WHERE p.companyid = 100

我已经看到了左外连接的典型实现(即into x from y in x.DefaultIfEmpty() 等),但不确定如何引入其他连接条件(AND f.otherid = 17

编辑

为什么AND f.otherid = 17 条件是 JOIN 的一部分而不是 WHERE 子句中的一部分? 因为某些行可能不存在f,我仍然希望包含这些行。如果在 WHERE 子句中应用条件,则在 JOIN 之后 - 那么我不会得到我想要的行为。

不幸的是:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100 && fgi.otherid == 17
select f.value

好像是这样的:

SELECT f.value
FROM period as p 
LEFT OUTER JOIN facts AS f ON p.id = f.periodid 
WHERE p.companyid = 100 AND f.otherid = 17

这不是我想要的。

【问题讨论】:

  • 甜蜜!我一直在寻找这个,但不知道如何搜索这个。不知道如何在这个答案中添加标签。这是我使用的搜索条件: linq to sql filter in join 或 from linq to sql where 子句 in join 或 from

标签: c# sql linq linq-to-sql outer-join


【解决方案1】:

您需要在致电DefaultIfEmpty() 之前介绍您的加入条件。我只会使用扩展方法语法:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.Where(f => f.otherid == 17).DefaultIfEmpty()
where p.companyid == 100
select f.value

或者您可以使用子查询:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in (from f in fg
             where f.otherid == 17
             select f).DefaultIfEmpty()
where p.companyid == 100
select f.value

【讨论】:

  • 感谢您在 from ....defaultifempty 语句上分享 .Where 限定符。我不知道你能做到。
【解决方案2】:

这也有效,...如果您有多个列连接

from p in context.Periods
join f in context.Facts 
on new {
    id = p.periodid,
    p.otherid
} equals new {
    f.id,
    f.otherid
} into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100
select f.value

【讨论】:

    【解决方案3】:

    我知道“有点晚了”,但以防万一有人需要在 LINQ 方法语法中执行此操作(这就是我找到这篇文章的原因最初),这将是如何做到这一点:

    var results = context.Periods
        .GroupJoin(
            context.Facts,
            period => period.id,
            fk => fk.periodid,
            (period, fact) => fact.Where(f => f.otherid == 17)
                                  .Select(fact.Value)
                                  .DefaultIfEmpty()
        )
        .Where(period.companyid==100)
        .SelectMany(fact=>fact).ToList();
    

    【讨论】:

    • 看 lambda 版本非常有用!
    • .Select(fact.Value) 应该是.Select(f => f.Value)
    【解决方案4】:

    另一个有效的选择是将连接分布在多个 LINQ 子句中,如下所示:

    public static IEnumerable<Announcementboard> GetSiteContent(string pageName, DateTime date)
    {
        IEnumerable<Announcementboard> content = null;
        IEnumerable<Announcementboard> addMoreContent = null;
            try
            {
                content = from c in DB.Announcementboards
                  // Can be displayed beginning on this date
                  where c.Displayondate > date.AddDays(-1)
                  // Doesn't Expire or Expires at future date
                  && (c.Displaythrudate == null || c.Displaythrudate > date)
                  // Content is NOT draft, and IS published
                  && c.Isdraft == "N" && c.Publishedon != null
                  orderby c.Sortorder ascending, c.Heading ascending
                  select c;
    
                // Get the content specific to page names
                if (!string.IsNullOrEmpty(pageName))
                {
                  addMoreContent = from c in content
                      join p in DB.Announceonpages on c.Announcementid equals p.Announcementid
                      join s in DB.Apppagenames on p.Apppagenameid equals s.Apppagenameid
                      where s.Apppageref.ToLower() == pageName.ToLower()
                      select c;
                }
    
                // Add the specified content using UNION
                content = content.Union(addMoreContent);
    
                // Exclude the duplicates using DISTINCT
                content = content.Distinct();
    
                return content;
            }
        catch (MyLovelyException ex)
        {
            // Add your exception handling here
            throw ex;
        }
    }
    

    【讨论】:

    • 不会比在单个 linq 查询中完成整个操作要慢吗?
    • @umar-t,很可能是的,考虑到这是八年前我写这篇文章的时候。我个人喜欢 Dahlbyk 在这里提出的相关子查询stackoverflow.com/a/1123051/212950
    • “联合”与“交叉连接”是不同的操作。这就像加法与乘法。
    • @Suncat2000,感谢您的指正。感恩节快乐! ???
    【解决方案5】:

    可以使用复合连接键编写。此外,如果需要从左右两侧选择属性,LINQ 可以写成

    var result = context.Periods
        .Where(p => p.companyid == 100)
        .GroupJoin(
            context.Facts,
            p => new {p.id, otherid = 17},
            f => new {id = f.periodid, f.otherid},
            (p, f) => new {p, f})
        .SelectMany(
            pf => pf.f.DefaultIfEmpty(),
            (pf, f) => new MyJoinEntity
            {
                Id = pf.p.id,
                Value = f.value,
                // and so on...
            });
    

    【讨论】:

      【解决方案6】:

      虽然我在下面的回答没有直接回答这个问题,但我相信它为阅读可能会发现有价值的核心问题提供了一个替代方案。

      我最终在这个线程和其他人寻找我编写的简单自联接 SQL 的 EF 等效项。我在我的项目中加入了 Entity Framework 以使我的数据库交互更容易,但是必须使用 "GroupJoin" 、 "SelectMany" 和 "DefaultIfEmpty" 就像必须翻译成另一种语言一样。

      此外,我与擅长 SQL 但 C# 技能有限的工程师一起工作。所以我想要一个他们可以阅读的解决方案。

      对我有用的解决方案是:

      context.Database.SqlQuery<Class>
      

      这允许执行 SQL 命令并在类型化对象中返回结果。只要返回的列名与给定类的属性名匹配。例如:

       public class MeasurementEvent
      {
          public int ID { get; set; }
          public string JobAssemID { get; set; }
          public DateTime? InspDate { get; set; }
      
      
      }
      
      var list = context.Database.SqlQuery<MeasurementEvent>(@"
                      Select op.umeMeasurementEventID as ID, op.umeJobID+'.'+Cast(op.umeAssemblyID as varchar) as JobAssemID ,  insp.umeCreatedDate as InspDate 
                      from uMeasurementEvents as op 
                          left JOIN   uMeasurementEvents as insp on op.umeJobID = insp.umeJobID and op.umeAssemblyID = insp.umeAssemblyID and insp.umeInstanceId = 1 and insp.umeIsInspector = 1
                        where  op.umeInstanceId = 1  and op.umeIsInspector = 0")
                  .ToList();
      

      【讨论】:

        【解决方案7】:

        在我看来,在尝试翻译之前考虑对您的 SQL 代码进行一些重写是有价值的。

        就个人而言,我会将这样的查询编写为联合(尽管我会完全避免空值!):

        SELECT f.value
          FROM period as p JOIN facts AS f ON p.id = f.periodid
        WHERE p.companyid = 100
              AND f.otherid = 17
        UNION
        SELECT NULL AS value
          FROM period as p
        WHERE p.companyid = 100
              AND NOT EXISTS ( 
                              SELECT * 
                                FROM facts AS f
                               WHERE p.id = f.periodid
                                     AND f.otherid = 17
                             );
        

        所以我想我同意@MAbraham1 回答的精神(尽管他们的代码似乎与问题无关)。

        但是,该查询似乎被明确设计为生成包含重复行的单列结果——实际上是重复的空值!很难不得出这种方法存在缺陷的结论。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2010-09-21
          • 1970-01-01
          • 2010-09-09
          • 2012-01-08
          • 2013-06-13
          • 1970-01-01
          相关资源
          最近更新 更多