Creating reusable chunks of Linq to SQL

Posted by tia on Stack Overflow See other posts from Stack Overflow or by tia
Published on 2011-01-12T03:47:59Z Indexed on 2011/01/12 3:53 UTC
Read the original article Hit count: 249

Filed under:
|

Hi,

I am trying to break up horrible linq to sql queries to make them a bit more readable.

Say I want to return all orders for product which in the previous year had more than 100 orders. So, original query is:

from o in _context.Orders
where (from o1 in _context.Orders 
       where o1.Year == o.Year - 1 && o1.Product == o.Product select o1).Count() > 100
select o;

Messy.

What I'd like to be able to do is to be able to break it down, eg:

private IEnumerable<Order> LastSeasonOrders(Order order)
{
    return (from o in _context.Orders 
            where o.Year == order.Year - 1 && o.Product == order.Product select o);

}

which then lets me change the original query to:

from o in _context.Orders
where LastSeasonOrders(o).Count() > 100
select o;

This doesn't seem to work, as I get method Blah has no supported translation to SQL when the query is run.

Any quick tips on the correct way to achieve this?

© Stack Overflow or respective owner

Related posts about LINQ

Related posts about linq-to-sql