c# - Dynamically select column name using Linq to Entities (EF6) -


i want encapsulate common scenarios when using ef6. here's example:

   public class stringrequest : dbrequestproperty    {       public string name { get; set; }       public bool? exactmatch { get; set; }        protected override bool isvalid()       {          return !string.isnullorwhitespace(name);       }        private bool requestexactmatch()       {          return exactmatch.hasvalue && exactmatch.value;       }        protected override iqueryable<t> execute<t>(iqueryable<t> original, string propertyname)       {          return requestexactmatch()             ? original.where(o => getproperty<string>(o, propertyname) == name)             : original.where(o => getproperty<string>(o, propertyname).contains(name));       }    } 

but getproperty can't converted query. i'm thinking on selecting dynamically column using "propertyname".

  protected override iqueryable<t> execute<t>(iqueryable<t> original, string propertyname)   {      return requestexactmatch()         ? original.where(o => getcolumnbyname<string>(propertyname) == name)         : original.where(o => getcolumnbyname<string>(propertyname).contains(name));   } 

is possible? in advance.

you can dynamically create expression<func<t, bool>> using expression class this:

protected override iqueryable<t> execute<t>(iqueryable<t> original, string propertyname) {    var parameter = expression.parameter(typeof(t));    var property = expression.propertyorfield(parameter, propertyname);    var constant = expression.constant(name);     expression predicate;    if(requestexactmatch())      {            predicate = expression.equal(property, constant);        }    else     {       predicate = expression.call(property, "contains", null, constant);        }     var lambda = expression.lambda<func<t, bool>>(predicate, parameter);     return original.where(lambda); } 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -