我有以下 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
这不是我所追求的。
您需要在调用 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 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
我知道这“有点晚了”,但以防万一有人需要在 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();
.Select(fact.Value)
应该是 .Select(f => f.Value)
另一个有效的选择是将连接分布在多个 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 可以写为
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...
});
虽然我在下面的回答并没有直接回答这个问题,但我相信它为阅读可能会发现有价值的核心问题提供了替代方案。
我最终在这个线程和其他人寻找我编写的简单自连接 SQL 的 EF 等效项。我在我的项目中包含了实体框架以使我的数据库交互更容易,但是必须使用 "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();
在我看来,在尝试翻译之前考虑对您的 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 回答的精神(尽管他们的代码似乎与问题无关)。
但是,该查询似乎被明确设计为生成包含重复行的单列结果——实际上是重复的空值!很难不得出这种方法有缺陷的结论。