Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 231
mason Avatar asked Sep 24 '15 03:09

mason


1 Answers

Try .AsQueryable() method:

return Customers.Values.AsQueryable().Where(expression);
like image 100
Backs Avatar answered Nov 15 '22 21:11

Backs