从 Entity Framework 中的列表构建 where 语句

Build a where statement from a list in Entity Framework

我有一个字符串列表,我想用它来在 Entity Framework 中创建 where 语句。例如,如果我有一个字符串列表。

List<string> cars = = new(){"car1","car2", "car3"};

我想从列表中动态构建一个 where 子句

query = query.Where(a => a.car == "car1" || a.car == "car2" || a.car == "car3");

使用 LINQKit,您可以创建一些扩展方法来自动处理此问题:

// searchTerms - IEnumerable<TSearch> where one must match for a row
// testFne(row,searchTerm) - test one of searchTerms against a row
// dbq.Where(r => searchTerms.Any(s => testFne(r,s)))
public static IQueryable<T> WhereAny<T, TSearch>(this IQueryable<T> dbq, IEnumerable<TSearch> searchTerms, Expression<Func<T, TSearch, bool>> testFne) =>
    dbq.AsExpandable().Where(searchTerms.AnyIs(testFne));
public static IQueryable<T> WhereAny<T, TSearch>(this IQueryable<T> dbq, Expression<Func<T, TSearch, bool>> testFne, IEnumerable<TSearch> searchTerms) =>
    dbq.AsExpandable().Where(searchTerms.AnyIs(testFne));
public static IQueryable<T> WhereAny<T, TSearch>(this IQueryable<T> dbq, Expression<Func<T, TSearch, bool>> testFne, params TSearch[] searchTerms) =>
    dbq.AsExpandable().Where(searchTerms.AnyIs(testFne));

// searchTerms - IEnumerable<TSearch> where one must match for a row
// testFne(row,searchTerm) - test one of searchTerms against a row
// r => searchTerms.All(s => testFne(r,s))
public static Expression<Func<T, bool>> AnyIs<T, TSearch>(this IEnumerable<TSearch> searchTerms, Expression<Func<T, TSearch, bool>> testFne) {
    var pred = PredicateBuilder.New<T>();
    foreach (var s in searchTerms)
        pred = pred.Or(r => testFne.Invoke(r, s));

    return pred;
}

那么你可以这样做:

query = query.WhereAny(cars,(a, c) => a.car == c);

您还可以推出自己的简化 LINQKit light 环境来处理表达式构造。