When selecting data for a custom object from a LINQ to SQL Left Join, how can I specify a default for an attribute that may sometimes be null?
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,
开发者_StackOverflow AnswerStatus = (qtu.IsCorrect == null) ? "Not Attempted" : (qtu.IsCorrect) ? "Correct" : "Incorrect"
});
}
Seems to me the problem might be in your where
clause:
where qtu.UserID == UserID
Since when the DefaultIfEmpty
kicks in, your qtu
object will not contain a valid 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)
精彩评论