我在使用LINQ时遇到了一个问题,我想知道在存储库中是否有一个快速的解决方案
GetCompletePackQuestion(int id)
{
var query = from q in DbSet where q.id == id
join a in DbContext.Set<answers>() on id equals a.question_id
join cc in DbContext.Set<correct_answers>() on id equals cc.question_id
select new CompletePackModel
{
Id = q.id,
Question = q.question,
CorrectAnswer = cc.answers.id,
Answers = q.answers.Select(ans => ans.answer)
};
return query.SingleOrDefault();
}
CompletePackModel的Answers属性是一个字符串列表。所以问题是:一个问题有很多答案,所以虽然q.id是一个int,问题字符串和answer_id一个单一的id(好吧,我应该采取连接到id表中的字符串)…最后一个答案应该是一个列表……
有办法解决这个问题吗?
感谢为什么它在查询中给我3个结果而不是一个?
我假设您正在使用实体框架(基于我看到的DbContext对象)。在这种情况下,你的Question类应该已经有了答案的集合。然后,您需要执行如下操作:
select new CompletePackModel
{
Id = q.id,
Question = q.question,
CorrectAnswer = from answ in DbContext.Set<answers>() where answ.id == a.id select answ.answer,
Answers = q.answers.Select(a => a.answer).ToList()
};
这样行吗?
var query = from q in DbContext.Set<questions>()
join a in DbContext.Set<answers>() on q.id equals a.question_id
join cc in DbContext.Set<correct_answers>() on q.id equals cc.question_id
select new CompletePackModel
{
Id = q.id,
Question = q.question,
CorrectAnswer = cc.answer,
Answers = DbContext.Set<answers>().Where(answ => answ.question_id == q.id).ToList()
};