[英]Converting SQL Server query into linq
The query I'm trying to translate is: 我要翻译的查询是:
SELECT
MIN(BookCopies.id) as id, Books.title, Authors.name, Publishers.name
FROM
dbo.BookCopies
INNER JOIN
Books ON BookCopies.bookId = Books.id
INNER JOIN
Authors ON Books.authorId = Authors.id
INNER JOIN
Publishers ON BookCopies.publisherId = Publishers.id
WHERE
BookCopies.sold = 0
GROUP BY
Books.title, Authors.name, Publishers.name;
I'm trying to solve this problem for 3 hours and I can't... :/ 我试图解决这个问题3个小时,但我无法...:/
The Linq code: Linq代码:
var query = (from bc in db.BookCopies
join b in db.Books on bc.bookId equals b.id
join a in db.Authors on b.authorId equals a.id
join p in db.Publishers on bc.publisherId equals p.id
where (bc.sold == false && bc.price != null && bc.price != 0)
group bc by new {b.title, author = a.name, publisher = p.name} into gr
select new {gr.Key.title, gr.Key.author, gr.Key.publisher});
But it's not correct. 但这是不正确的。
Trick here is selecting result of joining into intermediate data type (row) which will be grouped later: 这里的技巧是选择加入中间数据类型(行)的结果,该结果将在以后分组:
from bc in db.BookCopies
join b in db.Books on bc.bookId equals b.id
join a in db.Authors on b.authorId equals a.id
join p in db.Publishers on bc.publisherId equals p.id
where bc.sold == 0
select new { bc.id, b.title, author = a.name, publisher = p.name } into row
group row by new { row.title, row.author, row.publisher } into g
select new {
id = g.Min(x => x.id),
g.Key.title,
g.Key.author,
g.Key.publisher
}
This produces exactly same query you are looking for. 这将产生与您要查找的查询完全相同的查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.