//Make this problem less complicated to explain by abstracting the inner join
//that we always need.
//For efficiency this should probably be put back in line
var A = from aq in answeredQuestions
from a in aq.Answers
from c in costs
where aq.QuestionID == c.QuestionID && a.ID == c.AnswerID
select new
{
QuestionText = aq.Question.Text,
AnswerText = a.Text,
Amount = c.Amount,
PropertySurveyID = aq.PropertySurveyID,
PropertySurvey = aq.PropertySurvey,
UnitsQuestionID = c.UnitsQuestionID,
UnitsQuestion = c.UnitsQuestion
};
//This is how to do it using the explicit join keyword
var B = from a in A
join lj in answeredQuestions on
new {
a.PropertySurveyID,
UnitsQuestionID = a.UnitsQuestionID.GetValueOrDefault(0)
}
equals new {
lj.PropertySurveyID,
UnitsQuestionID = lj.QuestionID
}
into unitQuestions
from uq in unitQuestions.DefaultIfEmpty()
select new PropertyCost(a.QuestionText,
a.AnswerText,
a.Amount,
uq == null ? 1 : uq.IntegerAnswer.GetValueOrDefault(1));
//I thought this might do it but the filter on the navigational property
//means it's equivalent to an inner join
var C = from a in A
from uq in a.PropertySurvey
.AnsweredQuestions
.Where(x => x.QuestionID == a.UnitsQuestionID)
select new PropertyCost(a.QuestionText,
a.AnswerText,
a.Amount,
uq == null ? 1 : uq.IntegerAnswer.GetValueOrDefault(1));
//This is the solution
//Back to the basics described by @CraigStuntz
//Just that we have to navigate further to get to the Units value
//Is this less "messy" than a join? Not sure. Maybe if you can think in Linq...
var D = from a in A
select new PropertyCost
(
a.QuestionText,
a.AnswerText,
a.Amount,
a.PropertySurvey
.AnsweredQuestions
.Where(x => x.QuestionID == a.UnitsQuestionID)
.FirstOrDefault() == null
?
1
: a.PropertySurvey
.AnsweredQuestions
.Where(x => x.QuestionID == a.UnitsQuestionID)
.FirstOrDefault()
.IntegerAnswer.GetValueOrDefault(1)
);
//And here I have further refined it by putting the initial inner join back
//inline and using the let keyword define how to retrieve the unit question.
//This makes it much more readable:
var E = from aq in answeredQuestions
from a in aq.Answers
from c in costs
let unitquestion = aq.PropertySurvey
.AnsweredQuestions
.Where(x => x.QuestionID == c.UnitsQuestionID)
.FirstOrDefault()
where aq.QuestionID == c.QuestionID && a.ID == c.AnswerID
select new
{
QuestionText = aq.Question.Text,
AnswerText = a.Text,
UnitCost = c.Amount,
NumUnits = unitquestion == null ? 1 : unitquestion.IntegerAnswer ?? 1,
};
我花了很长时间才得到这个。我仍然在 sql 中思考,我不禁想在实体框架中使用视图。请注意,我已对此进行了简化,仅显示 UnitQuestion 的第一个左连接