【问题标题】:MVC LINQ Test repositoryMVC LINQ 测试存储库
【发布时间】:2013-10-09 19:17:59
【问题描述】:

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

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'

请帮忙。

【问题讨论】:

  • 我收到Cannot convert type 'System.Collections.Generic.List&lt;object&gt;' to 'System.Collections.Generic.List&lt;T&gt;'

标签: c# asp.net-mvc linq


【解决方案1】:

您需要使用WhereIEnumerable&lt;T&gt; 版本,它需要Func&lt;T, bool&gt; 而不是IQueryable&lt;T&gt;,它需要Expression,例如

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

另外,List&lt;object&gt; 不能转换为 List&lt;T&gt; 我的建议是使外部类也通用,即

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

【讨论】:

    【解决方案2】:

    据我了解,您不能只将 objectList 转换为泛型类型 你应该做类似thisthis

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-28
      • 2013-01-20
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      相关资源
      最近更新 更多