0

问题: 我需要一个Listwith 类型resultAll,它应该在响应表中的每一行中包含一个项目。我得到的是这些对象的列表,但每个对象都是我的响应表中最后一行的对象。我什至更改了我的数据,它始终是最后一行。(按ID排序)

这是resultAll课程:

public class resultAll
{
public Response response = new Response();
public List<ResponseDetails> listofresponses = new List<ResponseDetails>();
public Question question = new Question();
public List<QuestionChoices> listofchoices = new List<QuestionChoices>();
}

这是我的麻烦代码:

List<Response> query1 = (from r in db.Responses
                                 select r).ToList();
        List<Question> query2 = (from r in db.Questions
                                 select r).ToList();
        List<ResponseDetails> subquery1 = (from r in db.Responses
                                           join w in db.ResponseDetails on r.ResponseId equals w.ResponseId
                                           select w).ToList();
        List<QuestionChoices> subquery2 = (from r in db.Questions
                                           join w in db.QuestionChoices on r.QuestionId equals w.QuestionId
                                           select w).ToList();

        List<resultAll> testlist = new List<resultAll>();
        resultAll temp = new resultAll();
        foreach (var r in query1)
        {
            temp.response = r;
            var subquery3 = (from d in query1
                            join f in query2 on d.QuestionId equals f.QuestionId
                            where d.ResponseId == r.ResponseId
                            select f).First();
            temp.question = subquery3;
            temp.listofresponses = (from d in subquery1
                                    where d.ResponseId == r.ResponseId
                                    select d).ToList();
            temp.listofchoices = (from d in subquery2
                                  where d.QuestionId == r.QuestionId
                                  select d).ToList();

            testlist.Add(temp);
        }

结果:我回来了Json(testlist.Select(x=> new {id=x.response.ResponseId, brierscore=x.response.brierScore}), JsonRequestBehavior.AllowGet)

这些是结果:[{"id":7,"brierscore":0.6498},{"id":7,"brierscore":0.6498},{"id":7,"brierscore":0.6498},{"id":7,"brierscore":0.6498}]

数据库信息:我有一个有 4 个实体的数据库。问题、问题选择、响应、响应详细信息。一个问题可以有多个回答。一个问题可以有多种选择。一个响应可以有多个 ResponseDetails。每个 responseDtail 都与一个问题选择相关联。

4

1 回答 1

2

你应该改变:

    resultAll temp = new resultAll();
    foreach (var r in query1)
    {

进入 :

    foreach (var r in query1)
    {
      resultAll temp = new resultAll();

否则,您总是将值分配给resultAll循环内的同一个实例,并将同一个实例添加到您的列表中。

一个新的循环迭代一次又一次地擦除在前一个循环中分配的值,直到循环结束。这就是为什么你得到最后一行 4 次。

于 2013-10-26T23:00:09.417 回答