[英]Cannot convert from Expression< Func< Entity, bool> > to Func< Entity, bool>
[英]How to invoke Expression<Func<Entity, bool>> against a collection
我有一个接口,从Repository模式定义一个存储库:
interface IRepository
{
List<Customer> GetAllCustomers(Expression<Func<Customer, bool>> expression);
}
我已经针对Entity Framework实现了它:
class EntityFrameworkRepository
{
public List<Customer> GetAllCustomers(Expression<Func<Customer, bool>> expression)
{
return DBContext.Customers.Where(expression).ToList();
}
}
这似乎运作良好,它允许我做类似的事情:
var customers = entityFrameworkRepository.Where(
customer => String.IsNullOrEmpty(customer.PhoneNumber)
);
现在我想要一个InMemoryRepository用于测试和演示目的。 我试图创建一个:
class InMemoryRepository
{
Dictionary<int, Customer> Customers {get; set;} = new Dictionary<int, Customer>();
public List<Customer> GetAllCustomers(Expression<Func<Customer, bool>> expression)
{
//what do I put here?
}
}
正如您在上面的代码中所看到的,我很难为InMemoryRepository.GetAllCustomers
实现做些什么。 我应该在那里用提供的表达式过滤Customers并返回结果?
我试过了:
return Customers.Where(expression));
但显然它期望Func<KeyValuePair<int, Customer>, bool>
所以我得到一个编译错误:
错误CS1929'Dictionary'不包含'Where'的定义和最佳扩展方法重载'Queryable.Where(IQueryable,Expression>)'需要类型为'IQueryable'DataAccess.InMemory的接收器
试试.AsQueryable()方法:
return Customers.Values.AsQueryable().Where(expression);
例
Expression<Func<Products, bool>> expresionFinal = p => p.Active;
if (mydate.HasValue)
{
Expression<Func<Products, bool>> expresionDate = p => (EntityFunctions.TruncateTime(c.CreatedDate) <= mydate);
expresionFinal = PredicateBuilder.And(expresionFinal, expresionDate );
}
IQueryable<T> query = dbSet;
query = query.Where(expresionFinal);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.