LINQ to SQL-具有多个联接条件的左外部联接


148

我有以下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某些行可能不存在,所以我仍然希望包含这些行。如果在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到sql过滤器或
联接中的

Answers:


243

您需要在致电之前介绍您的加入条件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

1
感谢您在from .... defaultifempty语句上共享.Where限定词。我不知道你能做到
Frank Thomas

28

如果您有多个列连接,也可以使用

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

12

我知道这是“ 有点晚了 ”,但是以防万一有人需要用LINQ Method语法来做到这一点(这就是为什么我最初找到这篇文章的原因),这就是这样做的方法:

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版本非常有用!
学习者

2
.Select(fact.Value)应该是.Select(f => f.Value)
Petr Felzmann '19

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查询中的整个操作慢吗?
Umar T.

@ umar-t,是的,很有可能,考虑到这是八年前我写的时候。我个人很喜欢Dahlbyk在此处假设的相关子查询 stackoverflow.com/a/1123051/212950
MAbraham1

1
“联合”是与“交叉联接”不同的操作。这就像加法还是乘法。
Suncat2000

1
@ Suncat2000,谢谢您的纠正。感恩节快乐!👪🦃🙏–
MAbraham1

0

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

在我看来,在尝试翻译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的回答的精神(尽管他们的代码似乎与问题无关)。

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.