Linq 相当于 Sql 查询
Linq equivalent to a Sql Query
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();
好像没有效果。
这就是我最终所做的,对我来说效果很好 -
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();
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();
好像没有效果。
这就是我最终所做的,对我来说效果很好 -
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();