Entity framework condidional query building

81 Views Asked by At

I have problem with creating complex query with entity framework. I would like to fetch additional data into my linq entity based on parameters given during construction of such query. Here is example with where:

        if (featureEnabled)
        {
            query = query.Where(n => *condition*);
        }

I have complex object created like that:

n => new Entity{
    Property = n.Something
    \* ... *\
    PropertyN = n.SomethingN,
}

and I want to load additional data into entity if feature is enabled (just like in where example):

public DoSomething(bool featureEnabled, feature2Enabled, etc.)
{
  return n => new Entity{
    Property = n.Something,
    \* ... *\
    PropertyN = n.SomethingN,
    Feature = (featureEnabled) ? *fetch some data from navigation property* : 0,
    Feature2 = (feature2Enabled) etc.
  }
}

In above example parameters (featureNEnabled) will be translated into sql parameters. How to perform such operation at query construction time?

2

There are 2 best solutions below

0
Shadow On BEST ANSWER

I finally found answer to my question on this blog With this code you may call expression.Merge(expression2) and initialization lists of two objects will be merged into one query.

5
Deepak Sharma On

did you mean inside the initializer you want use the if condition?

if its so i will have its not possible. To use the if condition you have to put it outside the initializer

var a = new MyClass{
prop1 = n.prop1,
prop2 = n.prop2,
prop3 = n.prop3,
};

a.propN = boolCondition ? n.PropN : 0;