Linq等效于Sql查询

时间:2018-10-31 07:45:52

标签: linq sql-to-linq-conversion

SQL查询-

select q.QuesId, q.Title, q.Description, count(a.QuesId) as Answers
from Question q
join Answer a on q.QuesId = a.QuesId
group by q.QuesId, q.Title, q.Description

我想将此Sql查询转换为linq。

我的方法是-

var questions = (from q in db.Questions
                 join a in db.Answers on q.QuesId equals a.QuesId
                 group q by new 
                 { q.QuesId, q.Title, q.Description, q.AskedBy, q.AskedOn, q.ModifiedOn }
                 into x
                 select new 
                 { x.Key.QuesId, x.Key.Title, x.Key.Description, x.Key.AskedBy, x.Key.AskedOn, x.Key.ModifiedOn, x.key.Answers.count }
                 ).ToList();

它似乎不起作用。

1 个答案:

答案 0 :(得分:1)

这是我最终所做的,对我来说很有效-

var questions = db.Questions
                .GroupJoin(db.Answers, q => q.QuesId, a => a.QuesId, (q, a) => q)
                .GroupBy(q => new { q.QuesId })
                .SelectMany(x => x.Select(q => new 
                { q.QuesId, q.Title, q.Description, q.UserDetail.FirstName, q.UserDetail.LastName, q.AskedOn, q.ModifiedOn, q.Answers.Count }
                )).Distinct();