首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >不能隐式地将类型'System.Linq.IQueryable<TMS.Models.CustomAsset>‘转换为“System.Collections.Generic.ICollection”

不能隐式地将类型'System.Linq.IQueryable<TMS.Models.CustomAsset>‘转换为“System.Collections.Generic.ICollection”
EN

Stack Overflow用户
提问于 2013-11-27 11:55:26
回答 3查看 12.4K关注 0票数 3

我有以下的模型课程:-

代码语言:javascript
复制
public class CustomerCustomAssetJoin
{
    public CustomAsset CustomAsset  { get; set; }
    public ICollection<CustomAsset> CustomAssets { get; set; }

} 

但当我写以下方法时:

代码语言:javascript
复制
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(),如下所示:

代码语言:javascript
复制
var customerAssets = tms.CustomAssets.Include(a => a.CustomAssetType).Where(a => a.CustomerName.ToLower() == customerName.ToLower());

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

EN

回答 3

Stack Overflow用户

发布于 2013-11-27 12:09:35

您在customerAssets中存储的只是一个查询--一种如何获取数据的方法。这还不是数据本身,因为它是懒洋洋的评估。ICollection<T>是为操作您已经拥有的数据集合而构建的接口。查询没有实现它,因此您不能隐式地将IQueryable<T>转换为ICollection<T>调用ToList(),这是一种简单的方法,可以强制将数据加载到ICollection<T>中,但在您的示例中,这也意味着在代码(和执行时间)中,查询将被执行,数据将从您正在查询的任何数据库中加载。

票数 8
EN

Stack Overflow用户

发布于 2013-11-27 12:12:56

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

票数 3
EN

Stack Overflow用户

发布于 2013-11-27 12:07:56

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20241810

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档