//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中,我不禁要被诱惑到Use Views in Entity Framework。请注意我已简化了此操作以仅显示第一个左连接到UnitQuestion
如果答案已经链接到问题为什么需要将成本链接到问题和答案,那么您肯定可以链接到问题? –
如果问题是“需要更换屋顶?”答案是“是”,那么c.Amount指定了一个成本。如果答案是“否”,那么没有成本。 – Colin
但是,UnitQuestion包含其IntegerAnswer属性中的值 - 因此没有链接到该关系中的单独答案 – Colin