Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 无法隐式转换类型';系统Linq.IQueryable<;TMS.Models.CustomAsset>';至';System.Collections.Generic.ICollection_C#_Asp.net Mvc_Asp.net Mvc 4 - Fatal编程技术网

C# 无法隐式转换类型';系统Linq.IQueryable<;TMS.Models.CustomAsset>';至';System.Collections.Generic.ICollection

C# 无法隐式转换类型';系统Linq.IQueryable<;TMS.Models.CustomAsset>';至';System.Collections.Generic.ICollection,c#,asp.net-mvc,asp.net-mvc-4,C#,Asp.net Mvc,Asp.net Mvc 4,我有以下模型类:- public class CustomerCustomAssetJoin { public CustomAsset CustomAsset { get; set; } public ICollection<CustomAsset> CustomAssets { get; set; } } 我得到了以下例外: 错误20无法隐式转换类型 “System.Linq.IQueryable”到 “System.Collections.Generic.

我有以下模型类:-

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

} 
我得到了以下例外:

错误20无法隐式转换类型 “System.Linq.IQueryable”到 “System.Collections.Generic.ICollection”。一 存在显式转换(是否缺少强制转换?)

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

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

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

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

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

这是因为您将
自定义资产定义为
ICollection
,而
IQueryable
不实现任何
ICollection
。您需要一个实现
ICollection
的结果,当您应用
ToList()
时,它将转换为一个
列表
,该列表实际上实现了
ICollection

ICollection和IQueryable是不同的东西@JohnJohn是的,除非您将
CustomAssets
重新定义为
IQueryable
,否则使用
ToList()
当然会正确运行查询并为您获取项目。
var customerAssets = tms.CustomAssets.Include(a => a.CustomAssetType).Where(a => a.CustomerName.ToLower() == customerName.ToLower());