在EF中使用左连接时获取空行

时间:2014-05-21 13:16:13

标签: c# sql entity-framework linq left-join

我在这里得到了非常不同类型的场景,我在4个表之间应用Left Join,没有表返回任何记录但是当我得到结果时,它显示1(一)个行的计数,所有值都设置为null。

这是我的代码:

var qry2 = (from p in dbModel.tbl_PROJECT

join c in dbModel.tbl_PROJECTxCOMPONENT
 on p.ProjectID equals c.ProjectID
  into list8
from l8 in list8.DefaultIfEmpty()

join a in dbModel.tbl_PROJECTCOMPONENT
on l8.ProjectComponentID equals a.ProjectComponentID
 into list9
from l9 in list9.DefaultIfEmpty()


join a in dbModel.tbl_COLOR
on l9.ColorID equals a.ColorID
 into list10
from l10 in list10.DefaultIfEmpty()

where p.ProjectID == projectId

select new ProjectDetails1
{
    Title = l9.Title,
    ColorId = l9.ColorID,
    ProjectComponentID = l9.ProjectComponentID,
    ColorDefinition = l10.ColorDefination
}).ToList();

click here

1 个答案:

答案 0 :(得分:2)

我可以使用以下SQL

重新创建您的问题

SQL

create table tbl_PROJECT
(
   ProjectID int identity(1,1) primary key,
   Title varchar(255)
)

create table tbl_COLOR
(
   ColorID int identity(1,1) primary key,
   ColorDefination varchar(255)
)

create table tbl_PROJECTCOMPONENT
(
   ProjectComponentID int identity(1,1) primary key,
   ColorID int not null references tbl_COLOR(ColorID),
   Title varchar(255)
)

create table tbl_PROJECTxCOMPONENT
(
   ProjectID int not null references tbl_PROJECT(ProjectID),
   ProjectComponentID int not null references tbl_PROJECTCOMPONENT(ProjectComponentID)
)

没有插入数据行,我尝试在LINQPAD中运行等效的LINQ。

LINQ

from p in Tbl_PROJECTs
join c in Tbl_PROJECTxCOMPONENTs on p.ProjectID equals c.ProjectID into list8

from l8 in list8.DefaultIfEmpty()
join a in Tbl_PROJECTCOMPONENTs on l8.ProjectComponentID equals a.ProjectComponentID into list9

from l9 in list9.DefaultIfEmpty()
join a in Tbl_COLORs on l9.ColorID equals a.ColorID into list10

from l10 in list10.DefaultIfEmpty()
where p.ProjectID == 1
select new 
{
    Title = l9.Title,
    //ColorId = l9.ColorID,
    //ProjectComponentID = l9.ProjectComponentID,
    ColorDefinition = l10.ColorDefination
}

在进行了几次更改以满足必须使用anon对象后,我们会得到一行空值,正如您所指出的那样。有趣的是 - ToList()删除了空行 问题是你的where子句是加入原始表" p"而不是你加入的表" list8"。
where p.ProjectID == 1where list8.ProjectID == 1交换,它应该可以正常工作。