c# - How can I do a Func<object[],Expression<Func<T,bool>>> dynamic? -


i working on doing .find(objects[] keys) method dynamically creates lambda function query database.

basically want is:

var mykeys = new guid("37ec1659-b35e-46c9-a7fc-e9802644ca1a"); iqueryable<t> database ; func<object[],expression<func<t,bool>>> objectfinder = createkeyexpression(typeof(t)); var foundobject = database.firstordefault(objectfinder(mykeys)); 

and

private lambdaexpression createkeyexpression(type c1type) {      parameterexpression instanceparameter = expression.parameter(c1type);     parameterexpression keyparameters = expression.parameter(typeof(object[]));      propertyinfo[] objectkeys = c1type.getkeyproperties().toarray();     var expr = expression.equal( expression.typeas( expression.property(instanceparameter,objectkeys[0]),typeof(object)),       expression.arrayindex(keyparameters,expression.constant(0)));        (int = 1; < objectkeys.length; i++)     {         expr = expression.andalso(expr, expression.equal(             expression.property(instanceparameter,objectkeys[i]),             expression.arrayindex(keyparameters,expression.constant(i))             ));       }      var lmp= expression.lambda(expr, instanceparameter);      return expression.lambda(lmp, keyparameters); } 

any ideas of how can achieve this? above gives me func<object[],func<t,bool>>, makes iqueryable ienumerable, meaning won't on database end.

you need use expression.constant method instead of expression.arrayindex, because not able pass expression array key values ​​using firstordefault method.

private static lambdaexpression createkeyexpression(type c1type, object[] parameters) {     var instanceparameter = expression.parameter(c1type);     propertyinfo[] objectkeys = c1type.getkeyproperties().toarray();      var expr = expression.equal(expression.property(instanceparameter, objectkeys[0]),         expression.constant(parameters[0], objectkeys[0].propertytype));       (int = 1; < objectkeys.length; i++)     {         expr = expression.andalso(expr, expression.equal(             expression.property(instanceparameter, objectkeys[i]),             expression.constant(parameters[i], objectkeys[i].propertytype)));     }     return expression.lambda(expr, instanceparameter); }  var parameters = new object[] { guid.newguid(), guid.newguid() }; var lambdaexpression = createkeyexpression(typeof(testclass), parameters); var testclasses = new list<testclass>() { new testclass { id = (guid)parameters[0], id1 = (guid)parameters[1] } }; var testclass = testclasses.asqueryable().firstordefault((expression<func<testclass, bool>>)lambdaexpression); 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -