简体   繁体   中英

Conditional generic Where equals clause in Entity Framework

I'm trying to create a where clause that I can pass in a func and a property then compare them. I have a long list of different properties I need to compare so I want an extension method to wrap it.

Here's how I want to use it:

string transactionNumber = "12345";
Queryable<TranCard> transactions = _context.TranCard
    .WhereEquals(t => t.TransactionNumber, transactionNumber)
    .ToList();

Here's the extension method I currently have that's causing me problems:

public static IQueryable<T> WhereEquals<T>(this IQueryable<T> source, Func<T, string> expression, string queryParam)
    {
        return source.Where(t => string.IsNullOrWhiteSpace(queryParam)
                                 || expression != null
                                 && string.Equals(queryParam.Trim(), expression.Invoke(t).Trim(), StringComparison.OrdinalIgnoreCase));
    }

When I try to run this it's throwing the following runtime error message: "Incorrect number of arguments supplied for call to method 'Boolean Equals(System.String, System.String, System.StringComparison)'"

I was able to get it to work by separating out the calls. This also made it more easy to read!

public static IQueryable<T> WhereEquals<T>(this IQueryable<T> source, Func<T, string> expression, string queryParam)
    {
        if (string.IsNullOrWhiteSpace(queryParam))
        {
            return source;
        }

        return source.Where(x => expression(x).Trim().ToLower() == queryParam.Trim().ToLower());
    }

Thanks to everyone for your help!

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