如何调用Expression <func <entity,bool =“”>&gt;针对集合

时间:2015-09-24 03:51:05

标签: c# linq iqueryable func

我有一个从Repository模式定义存储库的接口:

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

我已经针对实体框架实施了它:

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&#39;字典&#39;不包含&#39; Where&#39;的定义和最好的扩展方法重载&#39; Queryable.Where(IQueryable,Expression&gt;)&#39;需要一个类型为“IQueryable&#39; DataAccess.InMemory

2 个答案:

答案 0 :(得分:10)

尝试.AsQueryable()方法:

// input operator, overloaded as a friend
istream& operator >>(istream& ins, Date& d) {
    bool flag = false;
    string junk;

    ins>>d.month;
    // if an invalid month is detected throw a bad_month
    if(d.month < 1 || d.month > 12) {
        getline(ins,junk); // eat the rest of the line
        throw (bad_month(d.month));
    }
    // if the read has failed because of eof exit funtion
    if(ins.eof()) return ins;

    if(ins.peek() == '/') ins.ignore();
    ins>>d.day;

    // if an invalid day is detected throw a bad_day
    if(d.day < 1  || d.day > d.daysallowed[d.month]){
        getline(ins,junk); // eat the rest of the line
        throw (bad_day(d.month, d.day));
    }

    if(ins.eof()) return ins;
    if(ins.peek() == '/') ins.ignore();

    ins>>d.year;

    return ins;
}

答案 1 :(得分:-1)

实施例

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