0

I have the following scenario:

  • I have an unknown at compile time DbSet, which I get it via its type like:

    DbSet entities = _repository.Context.Set(myType)
    
  • I have a dynamically-built expression of a given type,

    Expression myFilter; //built as an expression of myType, constructed at runtime

How can I apply myFilter on entities, in order to filter out the entities based on myFilter?

Tamas Ionut
  • 4,240
  • 5
  • 36
  • 59
  • You need to convert your expression to lambda expression by calling Expression.Lambda, did you do that? Can you post little sample of how expression is generated? – Akash Kava Jul 17 '15 at 08:37

1 Answers1

1

below is a code that might help you: it finally creates a IQueryable of myType that actually represents something like SELECT * FROM YourMappedTable WHERE Id = 1 but of cource, instead of using my expression that i have built for demo purpose, you could use your expression.

class Program
{
    static void Main(string[] args)
    {
        using (var x = new DB01Entities ())
        {
            Type myType = typeof(Angajati);

            var setMethod = typeof(DB01Entities).GetMethods(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public).Where (a => a.Name == "Set" && a.IsGenericMethod).First ().GetGenericMethodDefinition ();

            var mySet = setMethod.MakeGenericMethod(myType);

            var realSet = mySet.Invoke(x, null);

            var param1 = Expression.Parameter(myType, "param1");

            var propertyExpresion = Expression.Property(param1, "Id");

            var idExpresssion = Expression.Constant(1);

            var body = Expression.Equal(propertyExpresion, idExpresssion);

            var lambda = Expression.Lambda(body, param1);

            var genericTypeCaster = typeof(Program).GetMethod("Caster", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic).GetGenericMethodDefinition();

            var effectiveMethod = genericTypeCaster.MakeGenericMethod(myType);

            var filteredQueryable = effectiveMethod.Invoke(null, new Object[] {realSet, lambda });
        }
    }

    private static IQueryable<T> Caster <T> (DbSet<T> theSet, Expression whereCondition) where T : class
    {
        return theSet.Where(whereCondition as Expression<Func<T, bool>>);
    }
}

So "lambda" variable above is the equivalent for your "myFilter". It must be at runtime an

Expression<Func<YourType, bool>>.

And mySet is your "entities' DbSet. Happy coding!

George Lica
  • 1,798
  • 1
  • 12
  • 23