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?

1 Answer 1

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.

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

1 Comment

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.

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.