Reputation: 32798
I have two entities:
public class AdminTest
{
public AdminTest()
{
this.AdminTestQuestions = new List<AdminTestQuestion>();
this.UserTests = new List<UserTest>();
}
public int AdminTestId { get; set; }
public string Title { get; set; }
public virtual ICollection<AdminTestQuestion> AdminTestQuestions { get; set; }
public virtual ICollection<UserTest> UserTests { get; set; }
}
public UserTest()
{
this.UserTestQuestions = new List<UserTestQuestion>();
}
public int AdminTestId { get; set; }
public int CreatedBy { get; set; }
public int UserTestId { get; set; }
public virtual AdminTest AdminTest { get; set; }
}
I can join these with a LEFT OUTER JOIN like this:
SELECT AdminTest.AdminTestId, AdminTest.Title, UserTest.CreatedBy FROM AdminTest
LEFT OUTER JOIN UserTest
ON AdminTest.AdminTestId = UserTest.AdminTestId
To give:
AdminTestId Title CreatedBy
1 A NULL
2 B 99
I also have a table that lists questions in each adminTest:
public partial class AdminTestQuestion
{
public int AdminTestQuestionId { get; set; }
public int AdminTestId { get; set; }
public System.Guid QuestionUId { get; set; }
public virtual AdminTest AdminTest { get; set; }
}
How could I modify my SQL to add in the additional table AdminTestQuestions to give the question Count like this:
AdminTestId Title Questions CreatedBy
1 A 10 NULL
2 B 20 99
I am using Linq with Entity Framework 6 so a LINQ or SQL solution would be good.
Upvotes: 1
Views: 51
Reputation: 14640
SQL
SELECT
AdminTest.AdminTestId,
AdminTest.Title,
COUNT(AdminTestQuestion.AdminTestQuestionId) Questions,
UserTest.CreatedBy
FROM
AdminTest LEFT OUTER JOIN UserTest
ON
AdminTest.AdminTestId = UserTest.AdminTestId JOIN AdminTestQuestion
ON
AdminTest.AdminTestId = AdminTestQuestion.AdminTestId
GROUP BY
AdminTest.AdminTestId, AdminTest.Title, UserTest.CreatedBy
LINQ
var query = from at in db.AdminTests
join ut in db.UserTests
on at.AdminTestId equals ut.AdminTestId into at_uts
from at_ut in at_uts.DefaultIfEmpty()
select new
{
at.AdminTestId,
at.Title,
Questions = at.AdminTestQuestions.Count(),
at_ut.CreatedBy
};
Upvotes: 1