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

问题描述 投票:144回答:6

我有以下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

这不是我想要的。

c# sql linq linq-to-sql outer-join
6个回答
236
投票

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

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

27
投票

这也可以,如果您有多个列连接,则也可以

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

12
投票

我知道这是“ 有点晚了”,但以防万一有人需要使用LINQ方法语法这是我最初找到这篇文章的原因)的情况,怎么做:

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

5
投票

另一个有效的选择是将联接分布在多个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();

0
投票

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

            //CROSS-JOIN this content
            content = content.Union(addMoreContent);

            //Exclude dupes - effectively OUTER JOIN
            content = content.Distinct();

            return content;
        }
    catch (MyLovelyException ex)
    {
        throw ex;
    }
}

-1
投票

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

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

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...
        });

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

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

© www.soinside.com 2019 - 2024. All rights reserved.