我试图在继承的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();


错误是“序列不包含任何元素”,我已经跟踪到此行:

join pto in context.TPM_USER on v.TPM_USER1.USERID equals pto.USERID


如果USER1为null,则不返回该行。相反,我需要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();

07-24 22:21