【问题标题】:Cannot implicitly convert type 'System.Linq.IQueryable<TMS.Models.CustomAsset>' to 'System.Collections.Generic.ICollection无法将类型“System.Linq.IQueryable<TMS.Models.CustomAsset>”隐式转换为“System.Collections.Generic.ICollection”
【发布时间】:2013-12-13 01:20:39
【问题描述】:

我有以下模型类:-

public class CustomerCustomAssetJoin
{
    public CustomAsset CustomAsset  { get; set; }
    public ICollection<CustomAsset> CustomAssets { get; set; }

} 

但是当我写了以下方法时:-

public CustomerCustomAssetJoin CustomerCustomAsset(string customerName)
{
    var customerAssets = tms.CustomAssets.Include(a => a.CustomAssetType).Where(a => a.CustomerName.ToLower() == customerName.ToLower());
    CustomerCustomAssetJoin caj = new CustomerCustomAssetJoin
    {
         CustomAsset = new CustomAsset {CustomerName = customerName },
         CustomAssets = customerAssets
    };
    return caj;  
 }

我遇到了以下异常:

错误 20 无法隐式转换类型 'System.Linq.IQueryable' 到 'System.Collections.Generic.ICollection'。一个 存在显式转换(您是否缺少演员表?)

那么是什么导致了这个错误?为了克服这个错误,我只需添加一个 .toList() 如下:

var customerAssets = tms.CustomAssets.Include(a => a.CustomAssetType).Where(a => a.CustomerName.ToLower() == customerName.ToLower());

那我为什么要把它转换成一个列表呢?

【问题讨论】:

标签: c# asp.net-mvc asp.net-mvc-4


【解决方案1】:

您在customerAssets 中存储的内容只是一个查询 - 一种方式,如何获取数据。它还不是数据本身,因为它是懒惰地评估的。 ICollection&lt;T&gt; 是一个为操作您已有的数据集合而构建的界面。该查询没有实现它,因此您不能从IQueryable&lt;T&gt; 隐式转换为ICollection&lt;T&gt; 调用ToList() 是一种如何强制将数据加载到ICollection&lt;T&gt; 的简单方法,但这也意味着在您的情况下,在代码中的那个位置(和执行时间),查询将被执行,数据将从您查询的任何数据库加载。

【讨论】:

    【解决方案2】:

    这是因为您将CustomAssets 定义为ICollection&lt;CustomAsset&gt;,而IQueryable&lt;T&gt; 没有实现任何ICollection&lt;T&gt;。您需要一个实现ICollection&lt;CustomAsset&gt; 的结果,当您应用ToList() 时,它会转换为实际上实现ICollection&lt;CustomAsset&gt;List&lt;CustomAsset&gt;

    【讨论】:

    • @JohnJohn 是的,除非您将 CustomAssets 重新定义为 IQueryable&lt;CustomAsset&gt;,否则使用 ToList() 当然会正确运行查询并为您获取项目。
    【解决方案3】:

    这是因为 LINQ Include 方法返回一个类型为 ObjectQuery(T) 的对象,它实现了 IQueryable&lt;T&gt; 接口,而您的类需要一个实现 ICollection&lt;T&gt; 接口的对象。由于这两个对象都不能从一个隐式转换为另一个,因此您必须将Include 方法的结果显式转换为List 类型,该类型确实实现了ICollection&lt;T&gt; 接口。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      • 2011-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多