从 LINQ to SQL Left Join 为自定义对象选择数据时,如何为有时可能为 null 的属性指定默认值?
更具体地说,请参阅下面的代码,我希望它始终返回 QuestionName 和 NodeID(它们始终一起存在),但是当没有 QuestionTracking 时,我希望它显示“未尝试”。然而到目前为止,如果有问题跟踪,我只能从该查询中获取结果。如果左连接上没有数据,如何在该字符串中获得“未尝试”?
public IQueryable<QuestionSummary> GetFullCourseQuestions(int CourseID, int RevisionID, int UserID)
{
return (from n in db.CourseNodes
join a in db.Assets on n.AssetID equals a.AssetID
join q in db.Questions on a.AssetID equals q.AssetID
join qt in db.QuestionTrackings on q.QuestionID equals qt.QuestionID into qu
where n.CourseID == CourseID && n.CourseRevisionID == RevisionID
from qtu in qu.DefaultIfEmpty()
where qtu.UserID == UserID
select new QuestionSummary
{
QuestionText = q.QuestionName,
NodeID = n.CourseNodeID,
AnswerStatus = (qtu.IsCorrect == null) ? "Not Attempted" : (qtu.IsCorrect) ? "Correct" : "Incorrect"
});
}
More specifically see the code below, I want it to ALWAYS return the QuestionName and the NodeID (they will always exist together) but when there is no QuestionTracking I want it to say 'Not Attempted'. However so far I am only getting results back from this query if there is a question tracking. How can I get "Not Attempted" in that string if and when there is no data on the left join?
public IQueryable<QuestionSummary> GetFullCourseQuestions(int CourseID, int RevisionID, int UserID)
{
return (from n in db.CourseNodes
join a in db.Assets on n.AssetID equals a.AssetID
join q in db.Questions on a.AssetID equals q.AssetID
join qt in db.QuestionTrackings on q.QuestionID equals qt.QuestionID into qu
where n.CourseID == CourseID && n.CourseRevisionID == RevisionID
from qtu in qu.DefaultIfEmpty()
where qtu.UserID == UserID
select new QuestionSummary
{
QuestionText = q.QuestionName,
NodeID = n.CourseNodeID,
AnswerStatus = (qtu.IsCorrect == null) ? "Not Attempted" : (qtu.IsCorrect) ? "Correct" : "Incorrect"
});
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在我看来,问题可能出在您的
where
子句中:因为当
DefaultIfEmpty
启动时,您的qtu
对象将不包含有效的用户ID
。Seems to me the problem might be in your
where
clause:Since when the
DefaultIfEmpty
kicks in, yourqtu
object will not contain a validUserId
.我认为 qtu.defaultifempty 将为默认值返回 null,因此当您检查 qtu.userid 时没有报告异常的事实表明您可能加入了错误的表。这意味着,在您正在测试的数据中,所有问题都有问题跟踪。我不知道你的数据库的结构,但也许你也可以尝试其他连接的外部连接? (抱歉,缺少格式,移动网站没有格式按钮)
I think qtu.defaultifempty will return null for the default value, so the fact that you aren't reporting an exception when you check qtu.userid suggests that you may be left joining on the wrong table. It means that, in the data you are testing, all questions have a question tracking. I don't know the structure of your db, but maybe you could try outer joins for the other joins as well? (sorry for lack of formatting, the mobile site doesn't have formatting buttons)