How to invoke Expression<Func<Entity, bool>> against a collection

邮差的信 提交于 2019-12-06 19:06:22

问题


I have an interface that defines a repository from the Repository pattern:

interface IRepository
{
    List<Customer> GetAllCustomers(Expression<Func<Customer, bool>> expression);
}

I've implemented it against Entity Framework:

class EntityFrameworkRepository
{
    public List<Customer> GetAllCustomers(Expression<Func<Customer, bool>> expression)
    {
        return DBContext.Customers.Where(expression).ToList();
    }
}

That seems to work well, it allows me to do something like:

var customers = entityFrameworkRepository.Where(
    customer => String.IsNullOrEmpty(customer.PhoneNumber)
);

Now I'd like to have an InMemoryRepository for testing and demo purposes. I attempted to create one:

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?
    }
}

As you can see in the above code, I'm stumped on what to do for InMemoryRepository.GetAllCustomers implementation. What should I do there to filter the Customers by the provided expression and return the results?

I tried:

return Customers.Where(expression));

But obviously it's expecting a Func<KeyValuePair<int, Customer>, bool> so I get a compilation error:

Error CS1929 'Dictionary' does not contain a definition for 'Where' and the best extension method overload 'Queryable.Where(IQueryable, Expression>)' requires a receiver of type 'IQueryable' DataAccess.InMemory


回答1:


Try .AsQueryable() method:

return Customers.Values.AsQueryable().Where(expression);



回答2:


Example

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);


来源:https://stackoverflow.com/questions/32753012/how-to-invoke-expressionfuncentity-bool-against-a-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!