2

我有一个看起来像这样的 dbml 上下文查询:

var SQLQueryResult = (from activeTable in context.activeTabless
                      where (
                               activeTable .AssignedTo == "Person1" ||
                               activeTable .AssignedTo == "Person2" ||
                               activeTable .AssignedTo == "Person3")
                    select new { ... });

我的问题是,如何根据用户选择更新该where字段,以便它可以具有任意数量or(不仅仅是上面的三个)?

假设数字可以来自列表或数组。使用直接 SQL 很简单,但不确定如何通过 Linq to SQL 来实现。

4

3 回答 3

6
var persons = new []{"Person1", "Person2", "Person3"};
var SQLQueryResult = (from activeTable in context.activeTabless
                      where ( persons.Contains(activeTable .AssignedTo))
                    select new { ... });

.Contains()您可以使用扩展方法检查集合中是否存在某些内容IEnumerable

于 2013-05-31T11:50:39.343 回答
1

您可以使用表达式动态创建查询,以便能够构建 where 谓词。您可以在此处找到更多详细信息和示例:Linq 动态查询

于 2013-05-31T11:52:04.907 回答
1

您可以使用谓词构建器(实用程序类):

using System;
using System.Linq;
using System.Linq.Expressions;

public static class PredicateBuilder {
  public static Expression<Func<T, bool>> Make<T>() { 
    return null; 
  }

  public static Expression<Func<T, bool>> Make<T>(this Expression<Func<T, bool>> predicate) {
    return predicate;
  }

  public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr, Expression<Func<T, bool>> orExpression) {
    if (expr == null) {
      return orExpression;
    }
    var invokedExpr = Expression.Invoke(orExpression, expr.Parameters.Cast<Expression>());
    return Expression.Lambda<Func<T, bool>>(Expression.Or(expr.Body, invokedExpr), expr.Parameters);
  }

  public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr, Expression<Func<T, bool>> andExpression) {
    if (expr == null) {
      return andExpression;
    }
    var invokedExpr = Expression.Invoke(andExpression, expr.Parameters.Cast<Expression>());
    return Expression.Lambda<Func<T, bool>>(Expression.And(expr.Body, invokedExpr), expr.Parameters);
  }
}

用法:

public IEnumerable<Squad> GetSquadsByIDs(IEnumerable<int> squadIDs) {
  if (squadIDs == null || !squadIDs.Any()) {
    throw new ArgumentNullException("squadIDs");
  }
  var condition = PredicateBuilder.Make<Squad>(s => false);
  foreach (var squadID in squadIDs) {
    int squadIDValue = squadID;
    condition = PredicateBuilder.Or<Squad>(condition, s => s.SquadID == squadIDValue);
  }
  var db = m_DalContextProvider.GetContext();
  return db.Squads.Where(condition);
}
于 2013-05-31T11:56:25.893 回答