Search code examples
c#linqprojectionentity-framework-6.1

Entity framework condidional query building


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?


Solution

  • 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.