1

Is it possible to refactor compiled LINQ to SQL queries? Suppose that I have a query with some logic, and I'd like to build onto it. Is it possible to reuse that query?

For example, suppose I have a basic query to get active items:

Func<DataContext, IQueryable<Item>> GetActiveItems =
    CompiledQuery.Compile((DataContext context) =>
        context.Items.Where(item => item.IsActive));

I'd like to build onto the above expression to make another query. The documentation of CompiledQuery indicates that I cannot apply another operator on the result of the compiled delegate. So what is the recommended way of refactoring such expressions?

I think I should be using an Expression, but how should it be used? Or is there a better way?

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Hosam Aly
  • 41,555
  • 36
  • 141
  • 182

1 Answers1

1

You can use something like PredicateBuilder to help with this:

The Albahari one is simple and works quite well although it's easy to extend or develop you own: http://www.albahari.com/nutshell/predicatebuilder.aspx

Obviously if your query relies on a local method that can't be translated to a SQL expression you'll have to rethink how you do it.

Tim Croydon
  • 1,866
  • 1
  • 19
  • 30
  • Thanks a lot. `PredicateBuilder` was not the best fit, but LinqKit's `Expand` method was exactly what I needed. If you could edit your answer to refer to it (preferably with a small example), I'd gladly accept it. – Hosam Aly Dec 30 '10 at 11:16