c# - Dynamic lambda expression (OrderBy) and nullable property type -
i'm trying dynamically create expression sort data database through entity framework. encountered 1 problem , cannot overcome it. maybe let me explain i'm trying do. goal create expression this:
x => x.property
where "property" name of property i'd specify dynamically.
now, let's go class, represents table in database (i simplified make things more clear):
public class mymodelclass { public long mylongproperty { get; set; } public decimal? mynullabledecimalproperty { get; set; } // important: it's nullable }
it code, i'm trying create expression described earlier:
// db entityframework context iqueryable<mymodelclass> list = db.mymodels.select(x => x); // x => var argument = expression.parameter(list.elementtype, "x"); // x.mynullabledecimalproperty var propertytoorder = expression.property(argument, "mynullabledecimalproperty"); // x => x.mynullabledecimalproperty var finalexpression = expression.call( typeof (queryable), "orderby", new[] { list.elementtype, typeof(icomparable) }, list.expression, expression.lambda<func<mymodelclass, icomparable>>(propertytoorder, argument)); list = list.provider.createquery<mymodelclass>(finalexpression);
problem occurs @ 4th statement (var finalexpression = expression.call(...)). exception:
expression of type „system.nullable`1[system.decimal]” cannot used return type „system.icomparable”.
as far understand problem me using "icomparable" type "mynullabledecimalproperty" nullable , nullable doesn't user icomparable interface. exception isn't thrown when i'm ordering "mylongproperty" or when replace "icomparable".
so questions:
what type should use make work nullable properties?
is possible use 1 type , work properties whether nullable or non-nullable.
notice: know can use ex. dynamic linq library, i'm not interested in solution - i'd learn how overcome without using 3rd party libraries.
there's no reason use icomparable
. indeed, many types comparable not implement icomparable
. use runtime type of whatever you're passing:
var finalexpression = expression.call( typeof (queryable), "orderby", new[] { list.elementtype, propertytoorder.type }, list.expression, expression.lambda(propertytoorder, new [] { argument }));
Comments
Post a Comment