c# - How to Perform ToString On Property of an Entity Framework Model Using Reflection -


i trying write "contains" query on properties of entity framework model.

i able following example no issues:

var students = db.students.asqueryable(); var test = students.where(x => x.firstname.tostring().tolower().contains("1")); 

however when using reflection (as shown in code below), following error returned:

linq entities not recognize method 'system.string tostring()' method, , method cannot translated store expression.

it's supposed supported now.

i have read on error, but see above tostring valid when using iqueryable (which required in case because don't want post filter data).

the main difference need invoke through reflection.

private static readonly methodinfo stringcontainsmethod =     typeof(string).getmethod(@"contains",         bindingflags.instance | bindingflags.public, null, new[] { typeof(string) }, null);  type dbtype = typeof(student);  var dbfieldmemberinfo = dbtype.getmember("firstname", bindingflags.ignorecase | bindingflags.public | bindingflags.instance).single();            // create "x" tdbtype var dbtypeparameter = expression.parameter(dbtype, @"x");  // @ x.firstname var dbfieldmember = expression.makememberaccess(dbtypeparameter, dbfieldmemberinfo);           // create criterion constant var criterionconstant = new expression[] { expression.constant(searchstring) };            var tostringmethod = typeof(convert).getmethod("tostring", type.emptytypes); var tostringcall = expression.call(dbfieldmember, tostringmethod); var fancycontain = expression.call(tostringcall, stringcontainsmethod, criterionconstant);  // create lambda x => x.firstname.tostring().contains(criterion) var lambda = expression.lambda(fancycontain, dbtypeparameter) expression<func<student, bool>>; 

this produces same exact lambda x.firstname.tostring().contains("") yet returns error tostring can't used. first example , fact added ef 6.1, can used. limitation of reflection?

looks issue stemming using convert.tostring() method in expression instead of type's individual implementation of tostring() method, e.g. tostringmethod = type.getmethod("tostring", type.emptytypes);


Comments

Popular posts from this blog

java - Spring Data JPA: Why findOne(id) executing delete query internally? -

python - Mongodb How to add addtional information when aggregating? -

java - Incorrect order of records in M-M relationship in hibernate -