无法将类型'System.Linq.IQueryable <TMS.Models.CustomAsset>'隐式转换为'System.Collections.Generic.ICollection

Joh*_*ohn 3 c# asp.net-mvc asp.net-mvc-4

我有以下模特课: -

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

} 
Run Code Online (Sandbox Code Playgroud)

但是当我写下面的方法时: -

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;  
 }
Run Code Online (Sandbox Code Playgroud)

我得到以下异常:

错误20无法将类型'System.Linq.IQueryable'隐式转换为'System.Collections.Generic.ICollection'.存在显式转换(您是否错过了演员?)

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

var customerAssets = tms.CustomAssets.Include(a => a.CustomAssetType).Where(a => a.CustomerName.ToLower() == customerName.ToLower());
Run Code Online (Sandbox Code Playgroud)

那么为什么我必须将其转换为列表?

Hon*_*tan 7

您存储的customerAssets内容只是一个查询 - 一种方式,如何获取数据.这还不是数据本身,因为它被懒惰地评估了.ICollection<T>是一个用于操作已有数据集合的接口.查询没有实现它,所以你不能隐式转换IQueryable<T>ICollection<T>Calling ToList()是一种简单的方法,如何强制将数据加载到一个ICollection<T>,但它也意味着在你的情况下,那个地方的代码(和执行时间)查询将被执行,数据将从您查询的任何数据库加载.