我在使用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)...最后一个一个a.answer应该是一个清单......
有没有办法解决这个问题?
由于
为什么它会在查询中给出3个结果而不是一个?
答案 0 :(得分:1)
我假设你正在使用Entity Framework(基于我看到的DbContext对象)。在这种情况下,您的问题类应该已经有一组答案。然后你需要做类似的事情:
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()
};
答案 1 :(得分:0)
这会起作用吗?
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()
};