我试图使用Linq连接两个表到sql,但是我收到错误
未将对象引用设置为对象的实例
我认为由于FirstOrDefault()方法,我改变了它,但错误仍然是!!!
这是我的代码:
LblCourseCode.Text = Request.QueryString["CourseCode"];
try
{
var qry = from cs in db.Courses
join inst in db.Instructors
on cs.CourseId equals inst.CourseId
where cs.CourseCode == "@CourseCode"
select new
{
//cs,
//inst
cs.CourseCode,
cs.CourseName,
cs.CourseAbout,
cs.CourseObjectives,
cs.CourseLearningOut,
inst.InstructorName,
cs.CourseImgUrl,
////instr = from ins in db.Instructors
//// select new { ins.InstructorName }
};
//LblCourseCode.Text = qry.courseCode;
LblCourseName.Text = qry.FirstOrDefault().CourseName;
LblCourseAbout.Text = qry.FirstOrDefault().CourseAbout;
LblObjectives.Text = qry.FirstOrDefault().CourseObjectives;
LblLearningOutcomes.Text = qry.FirstOrDefault().CourseLearningOut;
LblCourseInstructore.Text = qry.FirstOrDefault().InstructorName;
ImageCourseAb.ImageUrl = qry.FirstOrDefault().CourseImgUrl;
}
catch(Exception ex)
{
LblErr.Text = ex.Message;
}
}
答案 0 :(得分:1)
要处理集合为空的情况,您应该在查询之前添加一个检查:
if (qry.Any())
{
LblCourseName.Text = qry.FirstOrDefault().CourseName;
LblCourseAbout.Text = qry.FirstOrDefault().CourseAbout;
LblObjectives.Text = qry.FirstOrDefault().CourseObjectives;
LblLearningOutcomes.Text = qry.FirstOrDefault().CourseLearningOut;
LblCourseInstructore.Text = qry.FirstOrDefault().InstructorName;
}
而不是加入你可以做一个嵌套的foreach循环,它不漂亮,但它可能会帮助你找出问题所在:
var qry = new List<object>();
foreach (var cs in db.Courses.Where(c => c.CourseCode == "@CourseCode"))
{
foreach (var inst in db.Instructors)
{
if (inst.CourseId == cs.CourseId)
{
qry.Add(new
{
cs.CourseCode,
cs.CourseName,
cs.CourseAbout,
cs.CourseObjectives,
cs.CourseLearningOut,
inst.InstructorName,
cs.CourseImgUrl,
});
}
}
}