如何调用表达式来; Func键<实体,布尔>>针对集合 [英] How to invoke Expression<Func<Entity, bool>> against a collection

查看:134
本文介绍了如何调用表达式来; Func键<实体,布尔>>针对集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从系统信息库模式定义了存储库的接口:

 接口IRepository 
{
文件清单<客户> GetAllCustomers(表达式来; Func键<客户,布尔>>表达式);
}



我实现了这对实体框架:

 类EntityFrameworkRepository 
{
公开名单<客户> GetAllCustomers(表达式来; Func键<客户,布尔>>表达式)
{
返回DBContext.Customers.Where(表达).ToList();
}
}

这似乎运作良好,它可以让我做是这样的:

  VAR的客户= entityFrameworkRepository.Where(
客户= GT; String.IsNullOrEmpty(customer.PhoneNumber)
);

现在我想有用于测试和演示目的的InMemoryRepository。我试图创建一个:

 类InMemoryRepository 
{
字典< INT,客户和GT;客户{搞定;设置;} =新词典< INT,客户和GT;();

公开名单<客户> GetAllCustomers(表达式来; Func键<客户,布尔>>表达式)
{
//什么我放在这里?
}
}



正如你可以在上面的代码中所看到的,我米难倒什么为 InMemoryRepository.GetAllCustomers 的实施做。 ?我应该在那里做了提供表达式过滤客户并返回结果。



我试过:

 返回Customers.Where(表达)); 



但很明显,它期待 Func键< KeyValuePair< INT,客户>中布尔> ; ,所以我得到一个编译错误:




错误CS1929'字典'不包含'在哪里的定义'和最佳推广方法重载'Queryable.Where(IQueryable的,表达式>)'需要类型的接收器的IQueryable'DataAccess.InMemory



解决方案

尝试的 .AsQueryable()方法的:

 返回Customers.Values.AsQueryable(),其中(表达); 


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

解决方案

Try .AsQueryable() method:

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

这篇关于如何调用表达式来; Func键&LT;实体,布尔&GT;&GT;针对集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆