具有多个where条件的左外连接,LINQ给出空引用错误

时间:2014-02-19 09:25:32

标签: c# linq linq-to-sql linq-to-entities

我正在尝试在两个表上执行左外连接,我尝试了以下操作:

var EducationDetails = (from e in DataContext.HRM_EMP_EDUCATION.AsEnumerable().Where(x => x.EMP_CODE == Employee_Code)
                                from ex in DataContext.HRM_EDUCATION.Where(x => x.EDU_TYPE == "EXAM" && x.EDU_CODE == e.EXAM_CODE).DefaultIfEmpty()
                                select new HRM_EMP_EDUCATIONModel
                                {
                                    EXAM_NAME= ex.EDU_NAME==null? "N/A":ex.EDU_NAME
                                }).ToList();

当e.Exam代码为空时,我收到错误。我做错了什么?

1 个答案:

答案 0 :(得分:1)

将条件ex.EDU_NAME==null更改为ex==null?

因为左外连接ex可以为null,当你检查EDU_NAME属性为null时,它将抛出NullReferenceException

如果您需要检查exEDU_NAME是否为null,则可以更改以下条件

EXAM_NAME = (ex!= null || ex.EDU_NAME==null) ? "N/A":ex.EDU_NAME