Linq查询从三个表填充集合

时间:2017-09-21 15:02:54

标签: c# linq entity-framework-6

我有以下三个表:

activity.getSupportActionBar

我需要填充以下对象,我有ResponseId。

activity

我开始编写此方法,该方法将返回SurveyResponse对象的集合,但我不确定如何完成或返回我的集合的最佳方法

[SURVEY_QUESTIONS]
(
[QuestionId]
[SurveyId],
[Question],
[AnswerType] 
)

[SURVEY_ANSWERS]
(
[AnswerId],
[QuestionId],
[ResponseId],
[Answer]
)

[SURVEY_RESPONSES]
(
[ResponseId],
[SurveyId]
)

2 个答案:

答案 0 :(得分:0)

我认为这就是你要找的东西。

public static List<SurveyResponse> GetSurveyResponse(int responseId)
{
    using (CaseDatabaseEntities entities = BaseDAL.GetNewEntities())
    {
        SURVEY_RESPONSES sr = entities.SURVEY_RESPONSES
                                                .Where(r => r.ResponseId == responseId).FirstOrDefault();

        var Answers = entities.SURVEY_ANSWERS.Where(a => a.ResponseId == responseId).;
        var Questions = entities.SURVEY_QUESTIONS.Where(q => q.SurveyId == sr.SurveyId);

        var questionsWithAnswers = (from q in Questions
                    join a in Answers on q.QuestionId equals a.QuestionId
                    select new SurveyResponse(){ ResponseId = a.responseId, Question = q.Question, Answer = a.Answer}).ToList()

        return questionsWithAnswers;

    }
}

我还没有测试过代码。

答案 1 :(得分:0)

最好使用Linq中的连接。假设答案表中的“ResponseId”列对应于调查答复表中的“ResponseId”列,您可以执行以下操作:

var responses = (from s in entities.SURVEY_RESPONSES 
                  join q in entities.SURVEY_QUESTIONS on s.SurveyId equals q.SurveyId
                  join a in entities.SURVEY_ANSWERS on s.ResponseId equals a.ResponseId
                  where s.ResponseId == responseId
                  select new {s.ResponseId, q.Question, a.Answer});

List<SurveyResponse> surveyResp = new List<SurveyResponse>();
foreach (var r in responses)
{
  SurveyResponse survey = new SurveyResponse();
  survey.ResponseId = r.ResponseId;
  survey.Question = r.Question;
  survey.Answer = r.Answer;
  surveyResp.Add(survey);
}

return surveyResp;