Jan
Jan

Reputation: 4216

dynamic projections in EF6

I am trying to create a dynamic projection with Entity Framework 6 but so far I failed. Depending on certain conditions I want to include or exclude certain data in the projection result.

Here is what would work:

Dim carQueryable = currentContext.Car.Include("ModellVariant.Modell.Make")

 if (includeEquipment) then
    return carQueryable.
        Select(Function(car) New CarFlatRecord With{
            .Fahrzeug = car,
            .ModellVariant = car.ModellVariant,
            .Modell = car.ModellVariant.Modell,
            .Make = car.ModellVariant.Modell.Make,
            .Equipment = car.Equiptment
            } )
 ELSE
    return carQueryable.
        Select(Function(car) New CarFlatRecord With{
            .Fahrzeug = car,
            .ModellVariant = car.ModellVariant,
            .Modell = car.ModellVariant.Modell,
            .Make = car.ModellVariant.Modell.Make} )
END IF

My problem is that I have already three binary conditions similar to includeEquipment. So the simple if/then solution would already require 8 different paths. I looked into Expressions as a solution but it seem EF is not capable of handling any complex scenarios.

I tried working with if() in the with-clause and this does produce the correctly populated output but in SQL the tables are still joined (which is my main concern I want to avoid).

(Answers in c# and vb are appreciated, that's why i crosstagged)

Upvotes: 0

Views: 315

Answers (1)

Jonathan Magnan
Jonathan Magnan

Reputation: 11347

When speaking of dynamic for Entity Framework, there is often 2 easy solutions (one free, one paid).

For both solutions, you will need to build a string containing your dynamic projection.

Free

LINQ Dynamic: https://github.com/kahanu/System.Linq.Dynamic/wiki/Dynamic-Expressions

A very popular library that allows easily to handle this scenario

var list = context.Customers.Select("new(Name, IsActive)").ToList();

I recommend this library if you want to handle most basic scenario

Paid

Disclaimer: I'm the owner of the project Eval-Expression.NET

This library is more powerful by using Expression Tree. It supports exactly the same syntax as C#

var list = context.Customers.SelectDynamic(x => "new { x.Name, x.IsActive }").ToList();

This library can be used for more complex scenarios. It let you compile and execute dynamic C# code at runtime.

Upvotes: 1

Related Questions