我有以下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
这不是我想要的。
答案 0 :(得分:230)
您需要在致电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 :(得分:25)
这也有效,...如果你有多个列连接
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
答案 2 :(得分:11)
我知道这是“有点迟了”但是如果有人需要在 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();
答案 3 :(得分: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;
}
//CROSS-JOIN this content
content = content.Union(addMoreContent);
//Exclude dupes - effectively OUTER JOIN
content = content.Distinct();
return content;
}
catch (MyLovelyException ex)
{
throw ex;
}
}
答案 4 :(得分: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...
});
答案 5 :(得分:-1)
在我看来,在尝试翻译它之前,考虑对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答案的精神(尽管他们的代码似乎与这个问题无关)。
但是,似乎查询明确设计为生成包含重复行的单个列结果 - 实际上是重复的空值!很难不得出这种方法存在缺陷的结论。
答案 6 :(得分:-1)
虽然我下面的回答没有直接回答这个问题,但我相信它提供了一个核心问题的替代方案,阅读可能会觉得有价值。
我最终在这个线程和其他人寻找等效于我编写的简单自连接 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();