问题:
我需要List
类型resultAll
,其响应表中的每一行都应包含一个项目。我得到的是这些对象的列表,但每个对象都是我的Response表中最后一行的对象。我甚至改变了我的数据,它始终是最后一行。 (按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个实体的数据库。问题,QuestionChoices,Response,ResponseDetails。一个问题可以有多个回复。一个问题可以有多种选择。响应可以有多个ResponseDetails。每个responseDtail都链接到一个Question选项。
答案 0 :(得分:2)
你应该改变:
resultAll temp = new resultAll();
foreach (var r in query1)
{
进入:
foreach (var r in query1)
{
resultAll temp = new resultAll();
否则,您总是将值分配给循环内的同一resultAll
实例,并将相同的实例添加到列表中。
新循环迭代一次又一次地擦除在前一个循环中分配的值,直到循环结束。这就是你最后一次获得4次的原因。