1

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... :/

The Linq code:

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.

2
  • 2
    Did you write any code during these 3 hours? Commented Sep 26, 2013 at 10:16
  • Yes, this: 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, a.name} into gr select new {bc.id, gr.Key.title, gr.Key.name}).Min(); Commented Sep 26, 2013 at 10:18

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.