MVC LINQ Test repository

本文关键字:repository Test LINQ MVC | 更新日期: 2023-09-27 18:33:51

我正在为依赖注入创建一个测试存储库,我在下面有我的测试方法。

private List<object> records;
public IList<T> GetFiltered<T>(Expression<Func<T, bool>> action = null) where T : class
{
    return ((List<T>)records).Where(action).ToList();
}

我本质上想要返回一个过滤的记录列表,其中"操作"条件为真。

我收到以下错误

错误 2 实例参数:无法从"System.Collections.Generic.List"转换为"System.Linq.IQueryable"

请帮忙。

MVC LINQ Test repository

您需要使用IEnumerable<T>版本的 Where 它期望Func<T, bool>而不是需要Expression IQueryable<T>

例如
public IList<T> GetFiltered<T>(Func<T, bool> action = null) where T : class
{
    return ((List<T>)records).Where(action).ToList();
}

另外,List<object>不能投射List<T>我的建议是使外部类也通用,即

public class MyContainer<T>
{
    private List<T> records;
    public IList<T> GetFiltered(Func<T, bool> action = null) where T : class
    {
        return records.Where(action).ToList();
    }
}

我了解,您不能只将objectList转换为泛型类型 你应该做这样或这样的事情