Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression<Func<T,bool>> adds an unwanted Convert when created in generic method

I have a function to generate an expression to be used in a linq Where clause.

public static Expression<Func<T,bool>> GetWhereCondition<T>() where T : IActive
{
    return x => x.Active;
}

(note IActive only defines the property 'Active')

There are other related functions and the idea is that i can inject the required conditions into a Generic class to control business rules, etc.

The problem is that when I run this, the returned Expression contains the lamda (seen from the debugger):

x => Convert(x).Active

Which is of course rejected by linq: 'LINQ to Entities only supports casting Entity Data Model primitive types.'

SO my question is...

How do I prevent this behaviour. There is no need for a conversion and clearly it is undesireable. Is it even possible to prevent this?

like image 886
Max Avatar asked Feb 01 '13 16:02

Max


2 Answers

Well, assuming this only needs to work with classes (the conversion is for boxing value-types), you can add a class constraint:

public static Expression<Func<T, bool>> GetWhereCondition<T>() where T : class, IActive
{
    return x => x.Active;
}

...and the conversion goes away.

like image 73
Ani Avatar answered Oct 31 '22 23:10

Ani


Try this:

public static Expression<Func<T, bool>> GetWhereCondition<T>() where T : IActive
{
    return x => x.Active;
}
like image 37
Hamlet Hakobyan Avatar answered Oct 31 '22 23:10

Hamlet Hakobyan