使用 MSDN 文章 "How to: Perform Left Outer Joins (C# Programming Guide)" 上找到的技术,我尝试在 Linq 代码中创建左外连接。本文提到使用 DefaultIfEmpty
方法从组连接创建左外连接。基本上,它指示程序包含左侧(第一个)集合的结果,即使右侧集合中没有结果。
但是,该程序的执行方式就像未指定外连接一样。
在我们的数据库中,AgentProductTraining
是我们的代理所参加的类(class)的集合。通常,如果不在 CourseMaterials
表中输入相应的值,则无法将Course
输入到其相应的表中。但是,这种情况偶尔可能会发生,因此,即使 AgentProductTraining
中列出了 Course
,但 CourseMaterials
中没有任何相应信息,我们希望确保返回结果>.
var training = from a in db.AgentProductTraining
join m in db.CourseMaterials on a.CourseCode equals m.CourseCode into apm
where
a.SymNumber == id
from m in apm.DefaultIfEmpty()
where m.EffectiveDate <= a.DateTaken
&& ((m.TerminationDate > a.DateTaken) | (m.TerminationDate == null))
select new
{
a.AgentProdTrainId,
a.CourseCode,
a.Course.CourseDescription,
a.Course.Partner,
a.DateTaken,
a.DateExpired,
a.LastChangeOperator,
a.LastChangeDate,
a.ProductCode,
a.Product.ProductDescription,
m.MaterialId,
m.Description,
a.Method
};
最佳答案
MSDN 示例使用新变量 subpet
:
var query = from person in people
join pet in pets on person equals pet.Owner into gj
from subpet in gj.DefaultIfEmpty()
select new { person.FirstName, PetName = (subpet == null ? String.Empty : subpet.Name) };
所以你必须使用你自己的“subpet”,我使用 submat
变量重写了你的代码:
var training = from a in db.AgentProductTraining
join m in db.CourseMaterials on a.CourseCode equals m.CourseCode into apm
where
a.SymNumber == id
from submat in apm.DefaultIfEmpty()
where
(submat.EffectiveDate <= a.DateTaken || submat.EffectiveDate == null) &&
(submat.TerminationDate > a.DateTaken || submat.TerminationDate == null)
select new
{
a.AgentProdTrainId,
a.CourseCode,
a.Course.CourseDescription,
a.Course.Partner,
a.DateTaken,
a.DateExpired,
a.LastChangeOperator,
a.LastChangeDate,
a.ProductCode,
a.Product.ProductDescription,
MaterialId = (submat==null?-1:submat.MaterialId),
Description = (submat==null?String.Empty:submat.Description),
a.Method
};
关于asp.net-mvc - Linq 左外连接无法使用 DefaultIfEmpty 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14965454/