Search code examples
c#linqlambdaexpression-trees

LINQ Expression tree avoid inner cast to object


Having this kind of expression Expression<Func<SampleType, object> sortField = entity => entity.UpdateDate where UpdateDate is a DateTime, when I debug into the expression body at runtime, the expression is translated like this Convert(entity.UpdateDate) casting it into a System.Object, that's the usual mechanic.

My issue has to do with an ORM driver that supports LINQ sort fields but it is unable to understand the Convert.

So, Is there a way to avoid this inner cast?

(the driver must be passed with Expression<Func<TEntity, object>> type)


Solution

  • If the required type is Expression<Func<TEntity, object>>, then you cannot create the tree without the cast. Either your ORM has to handle the cast (something along the lines as @Matias Cicero suggested), or you need to pass in an Expression<Func<TEntity, TProperty>>, which is how most of the ORMs handle it as far as I know.