我正在尝试执行此Linq表达式,但LEFT JOIN正在复制行
当我在SQL中编写这个完全查询时它可以正常工作,但是当我在Linq Expression中编写它时,LEFT JOIN会复制该行。
我试过分组......但是我得到了相同的结果。
var sql = (from project in db.Project
join suitT in db.SuitT
on project.Id equals suitT.IdProject
join inspec in db.Inspec
on suitT.Id equals inspec.IdSuitT
join listFinalDef in db.ListFinalDef
on inspec.Id equals listFinalDef.IdInspec
into myListFinalDef
from groupListFinalDef in myListFinalDef.DefaultIfEmpty()
join artefact1 in db.Artefact
on groupListFinalDef.Id equals artefact1.IdListFinalDef
into myArtefact1
from groupArtefact1 in myArtefact1.DefaultIfEmpty()
join artefact2 in db.Artefact
on inspec.Id equals artefact2.IdInspec
into myArtefact2
from groupArtefact2 in myArtefact2.DefaultIfEmpty()
join typeArtefact in db.TypeArtefact
on inspec.IdTypeArtefact equals typeArtefact.Id
where ...
select new ArtefactModels
{
IdArtefact1 = groupArtefact1.Id,
IdArtefact2 = groupArtefact2.Id,
...,
...,
...
}).ToList();
发生了什么:复制行
示例
Id: 1 | ProjectName: Project 1 | InspecTitle: Title 1
Id: 1 | ProjectName: Project 1 | InspecTitle: Title 1
Id: 2 | ProjectName: Project 2 | InspecTitle: Title 2
Id: 2 | ProjectName: Project 2 | InspecTitle: Title 2
我正在尝试做什么:
示例
Id: 1 | ProjectName: Project 1 | InspecTitle: Title 1
Id: 2 | ProjectName: Project 2 | InspecTitle: Title 2
编辑:
我正在尝试使用LINQ Expression执行此SQL:
SELECT art1.Id AS IdArtefact1, art2.Id AS IdArtefact2, ...
FROM
Project
INNER JOIN SuitT ON Project.Id = SuitT.IdProject
INNER JOIN Inspec ON SuitT.Id = Inspec.IdSuitT
LEFT JOIN ListFinalDef ON Inspec.Id = ListFinalDef.IdInspec
LEFT JOIN Artefact AS art1 ON ListFinalDef.Id = art1.IdListFinalDef
LEFT JOIN Artefact AS art2 ON Inspec.Id = art2.IdInspec
INNER JOIN TypeArtefact ON Inspec.IdTypeArtefact = TypeArtefact.Id
WHERE ...
答案 0 :(得分:2)
groupby是这样的:
var sql = (from project in db.Project
join suitT in db.SuitT
on project.Id equals suitT.IdProject
join inspec in db.Inspec
on suitT.Id equals inspec.IdSuitT
join listFinalDef in db.ListFinalDef
on inspec.Id equals listFinalDef.IdInspec
into myListFinalDef
from groupListFinalDef in myListFinalDef.DefaultIfEmpty()
join artefact1 in db.Artefact
on groupListFinalDef.Id equals artefact1.IdListFinalDef
into myArtefact1
from groupArtefact1 in myArtefact1.DefaultIfEmpty()
join artefact2 in db.Artefato
on inspec.Id equals artefact2.IdInspec
into myArtefact2
from groupArtefact2 in myArtefact2.DefaultIfEmpty()
join typeArtefact in db.TypeArtefact
on inspec.IdTypeArtefact equals typeArtefact.Id
where ...
select new ArtefactModels
{
IdArtefact1 = groupArtefact1.Id,
IdArtefact2 = groupArtefact2.Id,
...,
...,
...
})
//This will return IGroupable<key,value> with as key IdArtefact and as
//value an Enumerable of all the anonymous types with the same IdArtefact
.GroupBy(a => a.IdArtefact1)
//Select first value per IdArtefact if there's multiple
.Select(a => a.FirstOrDefault())
.ToList();
答案 1 :(得分:0)
您可以使用我的库PowerfulExtensions。它有Distinct
个属性方法,记录为here。
只需在LINQ链的末尾调用它,并传递使行与众不同的属性。