我有一个Linq表达式,可能会根据某些条件进行更改.我想做的一个例子(留空一点我不确定):
Expression<Func<Project, bool>> filter = (Project p) => p.UserName == "Bob";
if(showArchived)
{
// update filter to add && p.Archived
}
// query the database when the filter is built
IEnumerable<Project> projects = unitOfWork.ProjectRepository.Get(filter);
Run Code Online (Sandbox Code Playgroud)
如何更新过滤器以添加任何额外参数?
在检索所有记录时,我使用a Where来进一步过滤结果.但是,这导致对数据库的查询多于严格必要的查询.
IEnumerable<Project> projects = unitOfWork.ProjectRepository.Get(filter);
if(showArchived)
{
projects = projects.Where(p => p.Archived);
}
Run Code Online (Sandbox Code Playgroud)
Get方法使用GenericRepository模式:
public class GenericRepository<TEntity> where TEntity : class
{
internal ProgrammeDBContext context;
internal DbSet<TEntity> dbSet;
public GenericRepository(ProgrammeDBContext context)
{
this.context = context;
this.dbSet = context.Set<TEntity>();
}
public virtual IEnumerable<TEntity> Get(
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).ToList();
}
else
{
return query.ToList();
}
}
public virtual TEntity GetByID(object id)
{
return dbSet.Find(id);
}
public virtual void Insert(TEntity entity)
{
dbSet.Add(entity);
}
public virtual void Delete(object id)
{
TEntity entityToDelete = dbSet.Find(id);
Delete(entityToDelete);
}
public virtual void Delete(TEntity entityToDelete)
{
if (context.Entry(entityToDelete).State == EntityState.Detached)
{
dbSet.Attach(entityToDelete);
}
dbSet.Remove(entityToDelete);
}
public virtual void Update(TEntity entityToUpdate)
{
dbSet.Attach(entityToUpdate);
context.Entry(entityToUpdate).State = EntityState.Modified;
}
public virtual IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
{
return dbSet.SqlQuery(query, parameters).ToList();
}
}
Run Code Online (Sandbox Code Playgroud)
更新
根据Marc Gravell和David B的下面的代码创建了一些扩展方法,为我解决了这个问题
public static class LinqExtensionMethods
{
public static Expression<Func<T, bool>> CombineOr<T>(params Expression<Func<T, bool>>[] filters)
{
return filters.CombineOr();
}
public static Expression<Func<T, bool>> CombineOr<T>(this IEnumerable<Expression<Func<T, bool>>> filters)
{
if (!filters.Any())
{
Expression<Func<T, bool>> alwaysTrue = x => true;
return alwaysTrue;
}
Expression<Func<T, bool>> firstFilter = filters.First();
var lastFilter = firstFilter;
Expression<Func<T, bool>> result = null;
foreach (var nextFilter in filters.Skip(1))
{
var nextExpression = new ReplaceVisitor(lastFilter.Parameters[0], nextFilter.Parameters[0]).Visit(lastFilter.Body);
result = Expression.Lambda<Func<T, bool>>(Expression.OrElse(nextExpression, nextFilter.Body), nextFilter.Parameters);
lastFilter = nextFilter;
}
return result;
}
public static Expression<Func<T, bool>> CombineAnd<T>(params Expression<Func<T, bool>>[] filters)
{
return filters.CombineAnd();
}
public static Expression<Func<T, bool>> CombineAnd<T>(this IEnumerable<Expression<Func<T, bool>>> filters)
{
if (!filters.Any())
{
Expression<Func<T, bool>> alwaysTrue = x => true;
return alwaysTrue;
}
Expression<Func<T, bool>> firstFilter = filters.First();
var lastFilter = firstFilter;
Expression<Func<T, bool>> result = null;
foreach (var nextFilter in filters.Skip(1))
{
var nextExpression = new ReplaceVisitor(lastFilter.Parameters[0], nextFilter.Parameters[0]).Visit(lastFilter.Body);
result = Expression.Lambda<Func<T, bool>>(Expression.AndAlso(nextExpression, nextFilter.Body), nextFilter.Parameters);
lastFilter = nextFilter;
}
return result;
}
class ReplaceVisitor : ExpressionVisitor
{
private readonly Expression from, to;
public ReplaceVisitor(Expression from, Expression to)
{
this.from = from;
this.to = to;
}
public override Expression Visit(Expression node)
{
return node == from ? to : base.Visit(node);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 14
如果我理解这个问题,那么很可能是问题所在:
IEnumerable<Project> projects = unitOfWork.ProjectRepository.Get(filter);
Run Code Online (Sandbox Code Playgroud)
任何工作projects都将使用Enumerable,而不是Queryable; 它可能应该是:
IQueryable<Project> projects = unitOfWork.ProjectRepository.Get(filter);
if(showArchived)
{
projects = projects.Where(p => p.Archived);
}
Run Code Online (Sandbox Code Playgroud)
后者是可组合的,并且.Where应该按预期工作,在将其发送到服务器之前构建更严格的查询.
您的另一个选择是在发送之前重写要合并的过滤器:
using System;
using System.Linq.Expressions;
static class Program
{
static void Main()
{
Expression<Func<Foo, bool>> filter1 = x => x.A > 1;
Expression<Func<Foo, bool>> filter2 = x => x.B > 2.5;
// combine two predicates:
// need to rewrite one of the lambdas, swapping in the parameter from the other
var rewrittenBody1 = new ReplaceVisitor(
filter1.Parameters[0], filter2.Parameters[0]).Visit(filter1.Body);
var newFilter = Expression.Lambda<Func<Foo, bool>>(
Expression.AndAlso(rewrittenBody1, filter2.Body), filter2.Parameters);
// newFilter is equivalent to: x => x.A > 1 && x.B > 2.5
}
}
class Foo
{
public int A { get; set; }
public float B { get; set; }
}
class ReplaceVisitor : ExpressionVisitor
{
private readonly Expression from, to;
public ReplaceVisitor(Expression from, Expression to)
{
this.from = from;
this.to = to;
}
public override Expression Visit(Expression node)
{
return node == from ? to : base.Visit(node);
}
}
Run Code Online (Sandbox Code Playgroud)
或者以允许方便使用的方式重写:
using System;
using System.Linq.Expressions;
static class Program
{
static void Main()
{
Expression<Func<Foo, bool>> filter = x => x.A > 1;
bool applySecondFilter = true;
if(applySecondFilter)
{
filter = Combine(filter, x => x.B > 2.5);
}
var data = repo.Get(filter);
}
static Expression<Func<T,bool>> Combine<T>(Expression<Func<T,bool>> filter1, Expression<Func<T,bool>> filter2)
{
// combine two predicates:
// need to rewrite one of the lambdas, swapping in the parameter from the other
var rewrittenBody1 = new ReplaceVisitor(
filter1.Parameters[0], filter2.Parameters[0]).Visit(filter1.Body);
var newFilter = Expression.Lambda<Func<T, bool>>(
Expression.AndAlso(rewrittenBody1, filter2.Body), filter2.Parameters);
return newFilter;
}
}
class Foo
{
public int A { get; set; }
public float B { get; set; }
}
class ReplaceVisitor : ExpressionVisitor
{
private readonly Expression from, to;
public ReplaceVisitor(Expression from, Expression to)
{
this.from = from;
this.to = to;
}
public override Expression Visit(Expression node)
{
return node == from ? to : base.Visit(node);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10134 次 |
| 最近记录: |