gpt4 book ai didi

c# - 在运行时创建 lambda 表达式

转载 作者:太空狗 更新时间:2023-10-30 00:40:04 25 4
gpt4 key购买 nike

我有一个存储库类,它有一个定义如下的 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);

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

No generic method 'Where' on type 'System.Linq.Queryable' is compatible with the supplied type arguments and arguments. No type arguments should be provided if the method is non-generic.

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

最佳答案

如果你想构建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();

关于c# - 在运行时创建 lambda 表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31418069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com