LINQ to SQL - 多个连接条件的左外连接

159

我有以下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条件是连接的一部分而不是在WHERE子句中?因为对于某些行来说,f可能不存在,但我仍然希望包括这些行。如果将条件应用于JOIN之后的WHERE子句中,则无法获得所需的行为。

不幸的是,以下内容:

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 or from linq to sql where clause in join or from - Solburn
7个回答

262

在调用 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

32

如果你有多列连接,这也可以工作。

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

好的。只是提醒一下,匿名对象内成员的有效名称必须相匹配。 - greenoldman

17

我知道现在"有点晚"了,但以防有人需要使用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();

2
非常有用,能够看到Lambda版本! - Learner
3
".Select(fact.Value)" 应改为 ".Select(f => f.Value)"。修改后的代码应保持原意,同时更加易于理解。 - Petr Felzmann
注意。在我的测试中,这种方法不能产生理想的SQL。它不是添加额外的JOIN...ON条件,而是创建一个子查询,首先查找所有otherid == 17的事实,然后连接子查询结果而不是表格。这种方法往往会导致广泛的索引扫描,而不是使用旨在支持连接的索引。具体来说,子查询没有将其扫描的行限制为与外部序列“Periods”匹配的行。 - Timo
抱歉,我纠正一下:对于足够大的数据集,SQL Server将优化子查询,应用外部条件以适当地进行过滤。 - Timo

5

另一种有效的选择是将连接操作分散到多个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 查询来完成整个操作,速度不会比单个 LINQ 查询慢吗? - Umar T.
@umar-t,很可能是这样,考虑到我写这篇文章已经超过八年了。个人而言,我喜欢Dahlbyk在这里提出的相关子查询。https://dev59.com/3nNA5IYBdhLWcg3wBo9m#1123051 - MAbraham1
1
“联合”是一种不同于“交叉连接”的操作。这就像加法和乘法一样。 - Suncat2000
1
@Suncat2000,感谢您的纠正。感恩节快乐! - MAbraham1

1

可以使用复合连接键编写。如果需要从左侧和右侧选择属性,则可以将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...
        });

-1

虽然我的回答并没有直接回答问题,但我相信它提供了一个替代方案,对读者可能很有价值。

我在这个线程和其他线程中寻找 EF 等效的简单自连接 SQL。我将 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();

-3

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

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

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 的回答精神(尽管他们的代码似乎与问题无关)。

然而,查询似乎是专门设计为生成一个包含重复行的单列结果--甚至是重复的空值!很难不得出这种方法是有缺陷的结论。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接