简体   繁体   中英

Apply a dynamically-built expression on non-generic DbSet

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 ?

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM