如果没有找到项,LINQ表达式是否可以使用左连接或默认为空?
本文关键字:连接 默认 可以使 LINQ 是否 表达式 如果没有 | 更新日期: 2023-09-27 18:14:02
我试图追踪在我继承的web应用程序中的一些现有代码崩溃。我把它追溯到一个LINQ表达式:
var projInfo = (from v in context.TPM_PROJECTVERSION
join p in context.TPM_PROJECT on v.PROJECTID equals p.PROJECTID
join pto in context.TPM_USER on v.TPM_USER1.USERID equals pto.USERID
join pt in context.TPM_PROJECTTYPES on p.PROJECTTYPEID equals pt.PROJECTTYPEID
where v.PROJECTID == projectId && v.VERSIONID == versionId
select new
{
ProjectName = v.NAME,
ProjectType = pt.SHORTNAME,
ProjectDesc = v.DESCRIPTION,
BusinessLaunchData = p.BUSINESSLAUNCHDATE,
BusinessSponsor = (v.TPM_USER3.FIRSTNAME + " " + v.TPM_USER3.LASTNAME),
PrimaryTrainingOwner = (pto.FIRSTNAME + " " + pto.LASTNAME)
}).First();
错误是"Sequence contains no elements",我跟踪到这一行:
join pto in context.TPM_USER on v.TPM_USER1.USERID equals pto.USERID
如果USER1为空,则不返回该行。相反,我需要PrimaryTrainingOwner只是null或空白。基本上,我需要做一个LEFT JOIN,并在设置PrimaryTrainerOwner时检查这一点。有没有办法更新这个LINQ表达式来处理这种情况?谢谢!
我想我找到解决办法了。我很感谢任何关于这是否是最好的方法或语法或其他方面的评论。谢谢!
var projInfo = (from v in context.TPM_PROJECTVERSION
join p in context.TPM_PROJECT on v.PROJECTID equals p.PROJECTID
join pto in context.TPM_USER on v.TPM_USER1.USERID equals pto.USERID into primaryowner
from subpto in primaryowner.DefaultIfEmpty()
join pt in context.TPM_PROJECTTYPES on p.PROJECTTYPEID equals pt.PROJECTTYPEID
where v.PROJECTID == projectId && v.VERSIONID == versionId
select new
{
ProjectName = v.NAME,
ProjectType = pt.SHORTNAME,
ProjectDesc = v.DESCRIPTION,
BusinessLaunchData = p.BUSINESSLAUNCHDATE,
BusinessSponsor = (v.TPM_USER3.FIRSTNAME + " " + v.TPM_USER3.LASTNAME),
PrimaryTrainingOwner = subpto == null ? String.Empty : (subpto.FIRSTNAME + " " + subpto.LASTNAME)
}).First();