【发布时间】:2013-10-01 19:09:33
【问题描述】:
是否可以在 LINQ 查询中检查空值,当该值为空时,是否可以一次执行额外的(子)查询?
说明
我在我的数据库中声明了默认按钮,带有默认的描述。用户可以自定义这些按钮,这些设置存储在ButtonLocations 表中。现在,每个按钮都有一个标准的描述,用户可以编辑这个描述。当用户编辑描述时,它存储在我的数据库中的Descriptions 表中。
当我检索所有按钮时,我首先检查按钮是否具有特定描述(在 buttonlocations 中,带有左连接)。如果这不是真的(所以为空),我会检索默认描述。
目前,我获取所有实体及其描述,然后循环遍历所有实体以检查值是否为空。这会导致对数据库的多次查询。
var temp = (from bl in context.buttonLocations
join b in context.Buttons
on bl.ButtonID equals b.ButtonID into buttons
from button in buttons.DefaultIfEmpty()
join d in context.Descriptions
on new
{
ID = bl.ButtonLocationID,
langID = languageID,
originID = descriptionOriginID
}
equals new
{
ID = d.ValueID,
langID = d.LanguageID,
originID = d.DescriptionOriginID
}
into other
where bl.ButtonGroupID == buttonGroupId
from x in other.DefaultIfEmpty()
select new
{
Button = button,
ButtonLocation = bl,
Description = x
}).ToList();
// Retrieve default descriptions if no specific one is set
foreach (var item in temp)
{
if (item.Description == null)
{
item.Description = context.Descriptions
.FirstOrDefault(x => x.ValueID == item.Button.ButtonID && x.LanguageID == languageID && x.DescriptionOriginID == (short)DescriptionOriginEnum.Button);
}
}
【问题讨论】:
标签: c# linq entity-framework