简体   繁体   中英

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?

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.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM