c# - Apply a dynamically-built expression on non-generic DbSet -
i have following scenario:
i have unknown @ compile time dbset, via type like:
dbset entities = _repository.context.set(mytype)
i have dynamically-built expression of given type,
expression myfilter;
//built expression ofmytype
, constructed @ runtime
how can apply myfilter
on entities
, in order filter out entities based on myfilter
?
below code might you: creates iqueryable of mytype represents select * yourmappedtable id = 1 of cource, instead of using expression have built demo purpose, use 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) t : class { return theset.where(wherecondition expression<func<t, bool>>); } }
so "lambda" variable above equivalent "myfilter". must @ runtime
expression<func<yourtype, bool>>.
and myset "entities' dbset. happy coding!
Comments
Post a Comment