为什么实体框架中的Linq PredicateBuilder在此代码中不起作用?

时间:2016-11-21 06:12:57

标签: c# entity-framework linq predicatebuilder

我正在使用Entity Framework,我使用PredicateBuilder遇到了一个奇怪的问题。我想创造一个充满活力的条件'根据我的请求中的某些值的可用性。即使分配了谓词变量,它也没有被添加到底层的sql查询中。我已经检查了在SQL中执行的查询以及在代码中生成的查询。由于某种原因,两者都不会对谓词进行计数。

如果我错过了什么,请告诉我。任何帮助表示赞赏。

using (DataEntities entities = new DataEntities())
{
   var predicate = PredicateBuilder.True<VpSwiftBank>();
   if (request.BranchItem.Bank != null && !string.IsNullOrEmpty(request.BranchItem.Bank.Name))
       {
        predicate = predicate.Or(i => i.BankName!= null && i.BankName.ToLower().Contains(request.BranchItem.Bank.Name.ToLower()));
       }
      if (request.BranchItem.Country != null && !string.IsNullOrEmpty(request.BranchItem.Country.Name))
        {
        predicate = predicate.Or(i => i.CountryName != null &&  i.CountryName.ToLower().Contains(request.BranchItem.Country.Name.ToLower()));
        }
      if (request.BranchItem.City != null && !string.IsNullOrEmpty(request.BranchItem.City.Name))
        {
                    predicate = predicate.Or(i => i.CityName != null && i.CityName.ToLower().Contains(request.BranchItem.City.Name.ToLower()));
        }

      response.SwiftBankItem = entities.VpSwiftBank.AsExpandable().Where(predicate).ToList().Select(x => new SwiftBankItem
      {
        BankCode = x.BankCode,
        BankName = x.BankName,
        BranchCode = x.BranchCode,
        BranchName = x.BranchName,
        CityCode = x.CityCode,
        CityName = x.CityName,
        CountryCode = x.CountryCode,
        CountryName = x.CountryName,
        SwiftCode = x.SwiftCode
       }).ToArray();
}

上面的代码由于某种原因不能生成SQL where子句。

下面是我的PredicateBuilder扩展方法代码,

  public static class PredicateBuilder
{
    public static Expression<Func<T, bool>> True<T>() { return f => true; }
    public static Expression<Func<T, bool>> False<T>() { return f => false; }

    public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> expr1,
                                                        Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
              (Expression.OrElse(expr1.Body, invokedExpr), expr1.Parameters);
    }

    public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> expr1,
                                                         Expression<Func<T, bool>> expr2)
    {
        var invokedExpr = Expression.Invoke(expr2, expr1.Parameters.Cast<Expression>());
        return Expression.Lambda<Func<T, bool>>
              (Expression.AndAlso(expr1.Body, invokedExpr), expr1.Parameters);
    }
}

0 个答案:

没有答案