我有以下LINQ查询。问题是,当tblSurveys
总共只有20个时,它会返回13k的结果。我做错了什么?
from s in surveyContext.tblSurveys
from st in surveyContext.tblTypes_for_Surveys
from t in surveyContext.tblSurvey_Types
where (s.Survey_Date >= startDate && s.Survey_Date <= stopDate) &&
(s.Unsubstantiated ||
(st.SurveyID == s.SurveyID && st.SurveyTypeID == t.SurveyTypeID &&
t.UnsubstantiatedAvailable && (from d in surveyContext.tblDeficiencies
where d.SurveyID == s.SurveyID
select d.DeficiencyID).Count() == 0))
orderby s.Survey_Date
select s;
答案 0 :(得分:5)
我可以在那里看到交叉连接,请查看&lt; -------
from s in surveyContext.tblSurveys
from st in surveyContext.tblTypes_for_Surveys
from t in surveyContext.tblSurvey_Types
where (s.Survey_Date >= startDate && s.Survey_Date <= stopDate) &&
(s.Unsubstantiated || <-------
(st.SurveyID == s.SurveyID && st.SurveyTypeID == t.SurveyTypeID &&
t.UnsubstantiatedAvailable && (from d in surveyContext.tblDeficiencies
where d.SurveyID == s.SurveyID
select d.DeficiencyID).Count() == 0))
orderby s.Survey_Date
select s;
您似乎需要在此处执行左连接
答案 1 :(得分:1)
您的数据库中是否设置了外键和关系?如果是这样,您可以大大简化您的查询。我还建议在.dbml文件中重命名表,这样它们就不会以'tbl'为前缀。
如果您确实设置了关系,那么您的查询可能看起来像这样:
from s in surveyContext.tblSurveys
where (s.Survey_Date >= startDate && s.Survey_Date <= stopDate) &&
(s.Unsubstantiated ||
(s.tblTypes_for_Surveys.Any(st => st.tblSurvey_Type.UnsubstantiatedAvailable) && s.tblDeficiencies.Count() == 0))
orderby s.Survey_Date
select s;