Linq .Count()来自另一个带内连接的表(C#)

时间:2015-10-29 00:20:34

标签: c# mysql sql linq

所以我现在已经尝试了几个小时,但我仍然无法得到它

表格是这样的。

**Questions** 
   -  IDQuestion, IDSubject, DNI, others..
**Answers**
   - IDQuestion , IDAnswer, DNICreator, others..
**StudentsPersonalinformation (just to get names, nothing related to the answers)**
   - name, surname, DNI, others..

我想要做的是在linq查询中获取问题的答案数量。我已经拥有的是这个

var querySubjectQuestions = (from questions in db.questions
join studentspersonalinformation in db.studentspersonalinformation on questions.DNI equals studentspersonalinformation.DNI
where questions.IDSubject == IDSubject && questions.status == 1
select new
{
    IDQuestion = questions.IDQuestion,
    Title = questions.title,
    Date = questions.date,
    studentName = studentspersonalinformation.name,
    studentSurname = studentspersonalinformation.surname,
}).OrderByDescending(c => c.Date);

但是仍然不知道从哪个IDQuestion等于它正在查询的表中放置.Count的位置。

谢谢:)

2 个答案:

答案 0 :(得分:1)

var querySubjectQuestions = (from questions in db.questions
                             join studentspersonalinformation in db.studentspersonalinformation on questions.DNI equals studentspersonalinformation.DNI
                             where questions.IDSubject == IDSubject && questions.status == 1
                             select new
                             {
                                 IDQuestion = questions.IDQuestion,
                                 Title = questions.title,
                                 Date = questions.date,
                                 studentName = studentspersonalinformation.name,
                                 studentSurname = studentspersonalinformation.surname,
                                 noAnswers = (from answer in db.answers 
                                             where answer.IDQuestion == questions.IDQuestion)
                                             select answer).Count()
                              }).OrderByDescending(c => c.Date);

答案 1 :(得分:0)

如果没有数据库表的c#实体,这是我能做的最好的事情。

select new
{
    IDQuestion = questions.IDQuestion,
    Title = questions.title,
    Date = questions.date,
    studentName = studentspersonalinformation.name,
    studentSurname = studentspersonalinformation.surname,
    noAnswer = questions.Answers.Count()
}