【问题标题】:cannot implicitly convert type in LINQ无法在 LINQ 中隐式转换类型
【发布时间】:2013-11-14 23:00:57
【问题描述】:

我正要为数据列表构建一个 DTO。

return from p in db.Students.Find(Id).Courses
       select new CourseDTO
       {
           Id = p.Id,
           CourseName = p.CourseName
       };

但是,当我使用它时,我收到以下错误:

Cannot implicitly convert type 
'System.Collections.Generic.IEnumerable<Storage.Models.CourseDTO>' to 
'System.Collections.Generic.ICollection<Storage.Models.CourseDTO>'. 
An explicit conversion exists (are you missing a cast?)

谁能解释一下原因?

【问题讨论】:

  • 显示函数签名..

标签: c# linq asp.net-mvc-4 dto


【解决方案1】:
return (from p in db.Students.Find(Id).Courses
           select new CourseDTO
           {
               Id = p.Id,
               CourseName = p.CourseName

           }).ToList();

【讨论】:

  • 这不是首选...除非我必须获得List,否则我会将函数签名更改为IEnumerable
  • 当您想确保结果实现时,这实际上是首选,尽管 OP 没有说明这一点。
【解决方案2】:

你方法的返回类型是ICollection&lt;T&gt;,但查询返回一个IEnumerable&lt;T&gt;(或IQueryable&lt;T&gt;)。很可能无论如何您都不需要ICollection&lt;T&gt;,如果您需要,您希望该集合做什么?它不能用于操作数据库。如果您所做的只是查询数据库,则将方法的返回类型更改为IEnumerable&lt;T&gt;:

public IEnumerable<CourseDTO> MyMethod(int Id) 
{
    return from p in db.Students.Find(Id).Courses
           select new CourseDTO
           {
               Id = p.Id,
               CourseName = p.CourseName

           };
}

【讨论】:

  • 如果您不必返回List,则首选此解决方案,因为它消耗的内存更少。
  • +1 表示没有提供最简单的解决方案,而是闭着眼睛使用.ToList()..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多