我有以下的模型课程:-
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.IC业‘。存在显式转换(是否缺少强制转换?)
那么是什么导致了这个错误呢?为了克服这个错误,我只添加了一个.toList(),如下所示:
var customerAssets = tms.CustomAssets.Include(a => a.CustomAssetType).Where(a => a.CustomerName.ToLower() == customerName.ToLower());那我为什么要把它转换成一个列表呢?
发布于 2013-11-27 12:09:35
您在customerAssets中存储的只是一个查询--一种如何获取数据的方法。这还不是数据本身,因为它是懒洋洋的评估。ICollection<T>是为操作您已经拥有的数据集合而构建的接口。查询没有实现它,因此您不能隐式地将IQueryable<T>转换为ICollection<T>调用ToList(),这是一种简单的方法,可以强制将数据加载到ICollection<T>中,但在您的示例中,这也意味着在代码(和执行时间)中,查询将被执行,数据将从您正在查询的任何数据库中加载。
发布于 2013-11-27 12:12:56
这是因为您将CustomAssets定义为ICollection<CustomAsset>,而IQueryable<T>没有实现任何ICollection<T>。您需要一个实现ICollection<CustomAsset>的结果,当您应用ToList()时,它将转换为一个实际上实现了ICollection<CustomAsset>的List<CustomAsset>
发布于 2013-11-27 12:07:56
这是因为LINQ Include方法返回一个类型为ObjectQuery(T)的对象,该对象实现了IQueryable<T>接口,而您的类需要一个实现ICollection<T>接口的对象。由于这两个对象都不能隐式地从一个对象转换到另一个对象,因此必须显式地将Include方法的结果转换为List类型,这确实实现了ICollection<T>接口。
https://stackoverflow.com/questions/20241810
复制相似问题