c# - Dynamic Where filter through navigation Property -


i'm creating generic filter works great far (only interested in contains filters):

private static methodinfo contains = typeof(string).getmethod("contains"); private static expression<func<t, bool>> getfilter<t>(string propertyname, string value) {     var item = expression.parameter(typeof(t), "item");     var member = expression.property(item, propertyname);     var constant = expression.constant(value);     var body = expression.call(member, contains, constant);      return expression.lambda<func<t, bool>>(body, item); } 

is there way extend search navigation property? i'm new using expression i'm not sure try.

an example be:

public class {     public int bid { get; set; }     public b b { get; set; } }  public class b {     public string name { get; set; } }  dbcontext.as     .where(getfilter<a>("b.name", "hello world"))     .tolist(); 

but fails on expression.property("b.name") with:

instance property b.name not defined type a

you need create each member access sequentially each property in property path :

private static expression<func<t, bool>> getfilter<t>(string propertyname, string value) {     var item = expression.parameter(typeof(t), "item");      expression member = item;     foreach (var prop in propertyname.split('.'))     {         member = expression.property(member, prop);     }      var constant = expression.constant(value);     var body = expression.call(member, contains, constant);      return expression.lambda<func<t, bool>>(body, item); } 

Comments

Popular posts from this blog

neo4j - finding mutual friends in a cypher statement starting with three or more persons -

php - How to remove letter in front of the word laravel -

minify - Minimizing css files -