在运行时创建lambda表达式

时间:2015-07-14 21:55:01

标签: c# linq lambda

我有一个存储库类,其GetAsQueryable方法的定义如下:

public class Repository<TEntity> : IDisposable, IRepository<TEntity> where TEntity : class
{
    internal DbSet<TEntity> _DbSet;

    public virtual IQueryable<TEntity> GetAsQueryable(
         Expression<Func<TEntity, bool>> filter = null,
         Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
         string includeProperties = "")
    {
        IQueryable<TEntity> query = _DbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
            return orderBy(query);
        }
        else
        {
            return query;
        }
    }
}

在我的调用代码中,我通常执行以下操作:

IRepository<Tracking> repoTracking = new Repository<Tracking>(context);
IQueryable<Tracking> tracking = repoTracking.GetAsQueryable();
var results = tracking.Where(t => t.Status_Code_Id == 15).ToList();

这很有效;但是现在我希望能够在运行时构建发送到.Where的lambda。我尝试构建expression tree如下:

IRepository<Tracking> repoTracking = new Repository<Tracking>(context);
IQueryable<Tracking> tracking = repoTracking.GetAsQueryable();
var results = tracking.Where(t => t.Status_Code_Id == 15).ToList();

IRepository<Tracking> repoTracking = new Repository<Tracking>(context);
IQueryable<Tracking> tracking = repoTracking.GetAsQueryable();

ParameterExpression pe = Expression.Parameter(typeof (int), "Status_Code_Id");
LambdaExpression lambda = Expression.Lambda(Expression.Equal(pe, Expression.Constant(15)));
MethodCallExpression whereExpression = Expression.Call(
    typeof(Queryable),
    "Where",
    new Type[] { tracking.ElementType },
    tracking.Expression,
    lambda);

但是,这会产生以下异常:

  

类型'System.Linq.Queryable'上没有泛型方法'Where'与提供的类型参数和参数兼容。如果方法是非泛型的,则不应提供类型参数。

为什么我的Where实例上找不到Tracking方法?

2 个答案:

答案 0 :(得分:7)

如果您想动态构建t => t.Status_Code_Id == 15,则无需使用Where致电Expression。只需创建Expression<Func<TEntity, bool>>并将其传递给Where

ParameterExpression t = Expression.Parameter(typeof(Tracking), "t");
Expression statusCode = Expression.Property(t, "Status_Code_Id");
Expression comparison = Expression.Equal(statusCode, Expression.Constant(15));
Expression<Func<Tracking, bool>> lambda
    = Expression.Lambda<Func<Tracking, bool>>(comparison, t);
var results = tracking.Where(lambda).ToList();

答案 1 :(得分:0)

请记住,.Where()具有通用签名。使用lambda表达式时,您不必为其提供显式泛型参数,因为编译器可以为您推断类型,但是当您使用反射时,您需要根据类型创建一个通用签名来调用你正在处理的事情。