我有一个看起来像这样的查询,如果没有RegisteredInstructor,则会抛出错误。有没有办法解决这个问题或在linq查询期间检查?
viewModel.SpaceEvents = yogaSpace.YogaSpaceEvents.Where(j => j.EventDateTime >= DateTime.Now).Select(j => new EventResult
{
RegsiteredInstructorName = j.RegisteredInstructor.Name,
RegisteredInstructorId = j.RegisteredInstructor.RegisteredTeacherId,
RegisteredTeacherImage = j.RegisteredInstructor.RegisteredTeacherImage
}).ToList();
其中RegisteredInstructor是
public virtual Profile RegisteredInstructor { get; set; }
在我的YogaSpaceEvents实体中。
答案 0 :(得分:2)
试试这个。这可以解决您的错误,检查j.RegisteredInstructor
是否为空。
viewModel.SpaceEvents = yogaSpace.YogaSpaceEvents
.Where(j => j.EventDateTime >= DateTime.Now)
.Select(j => new EventResult
{
RegsiteredInstructorName = j.RegisteredInstructor!= null?j.RegisteredInstructor.Name:"",
RegisteredInstructorId = j.RegisteredInstructor!= null?j.RegisteredInstructor.RegisteredTeacherId:0,
RegisteredTeacherImage = j.RegisteredInstructor!= null?j.RegisteredInstructor.RegisteredTeacherImage:""
}).ToList();