简体   繁体   中英

C# Linq predicate generation remove all null values from list

I am trying to generate filter code using linq predicates. When I use a predicate with a object != null:

public static Expression<Func<ContactPermitsSearch, bool>> PermitNumberNotNull()
    {
        Expression<Func<ContactPermitsSearch, bool>> predicate = contactPermit => contactPermit.PermitNumber != null;
        return predicate;
    }

which is called by:

public static IQueryable<ContactPermitsSearch> FilterByNameMailingPermit(this IQueryable<ContactPermitsSearch> queryable, string search, bool filterOn)
    {
        var predicate = PredicateBuilder.True<ContactPermitsSearch>();

        predicate = predicate.And(PermitNumberNotNull());

        var filtered = queryable.AsExpandable().Where(predicate);
        return filtered;
    }

The SQL statement that is generated does not include the PermitNumberNotNull predicate statement.

Thoughts on fixing this?

There's nothing obviously wrong with the code. I'm sure that if you inspect predicate in the debugger after merging it with PermitNumberNotNull() you'll see that the not null predicate is part of the expression tree.

The only reasonable assumption is that EF knows that contactPermit.PermitNumber can't ever be null because it's required property. Therefore, it simply ignores the predicate.

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