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()
时,它将转换为一个列表
,该列表实际上实现了ICollectionICollection和IQueryable是不同的东西@JohnJohn是的,除非您将CustomAssets
重新定义为IQueryable
,否则使用ToList()
当然会正确运行查询并为您获取项目。
var customerAssets = tms.CustomAssets.Include(a => a.CustomAssetType).Where(a => a.CustomerName.ToLower() == customerName.ToLower());