Willis
Willis

Reputation: 171

Linq to entities if else condions in query

Using Linq to Entities to select multiple properties in a single query. I have if then else conditions in the lambda expressions to select properties like this:

Repository.Select(
x => Condition1 ? x.Property1 : x.Property2,
y => Condition2 ? y.Property1 : y.Property2,
z => .....);

The generated sql is unnecessarily complex. I'd like to get it to not include the if else conditions for a start. Is there a way to get it to evaluate the conditions i.e. to just

x=> x.Property1 

before generating the sql?

Upvotes: 1

Views: 2061

Answers (2)

cf_en
cf_en

Reputation: 1661

I guess it depends on whether the conditions are per data set or per row. If Condition1 will be either true or false for each row returned by the query, then it has to be submitted to the database for evaluation.

Otherwise Condition1, if it is true and can be evaluated as such in C# before running the query, will be true for every row, in which case you can evaluate in C# and do a different projection based on the outcome, e.g.

if (Condition1 && Condition2) {
    Repository.Select(x => x.Property1,
        y => y.Property1
} else if (...) {
    ...
}

Maybe not ideal for lots of conditions, but as far as I'm aware that would be one way to stop sending lots of conditions for the database to evaluate unnecessarily.

Upvotes: 1

pwas
pwas

Reputation: 3373

You want to evalute the condition and the server side right?

One of the possible ways is to write helper method:

public Expression<Func<TInput, TOutput>> ResolveProp<ITinput, TOutput>(
      Expression<Func<TInput, TOuput>> propSelector1,
      Expression<Func<TInput, TOuput>> propSelector2,
      bool condition){
  return condition ? propSelector1 : propSelector2;
}

Usage:

Repository.Select(ResolveProp<SomeEntity, PropType>(
                        x => x.Property1, 
                        x => x.Property2, 
                        Condition1),
                  ...)

ResolveProp returns single property selector as expression, based on condition. Selecting selector is done at server side, so your sql should get simplified.

Upvotes: 4

Related Questions