2013-11-14 146 views
4

我正要建立一个DTO的数据列表。不能隐式转换类型LINQ

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?) 

任何人都可以解释,为什么?

+2

显示函数签名.. –

回答

4

你方法的返回类型为ICollection<T>但查询返回IEnumerable<T>(或IQueryable<T>)。无论如何,你很可能不需要ICollection<T>,如果你这样做了,你会期待那个系列做什么?它不能用于操纵数据库。如果你正在做的是查询数据库,那么你的方法的返回类型更改为IEnumerable<T>

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

      }; 
} 
+0

如果您不必返回'List',则此解决方案是首选,因为它消耗的内存更少。 –

+0

+1不提供最简单的解决方案,并用'.ToList()'与你的眼睛关闭.. –

+0

感谢作品像一个魅力 – tamikoon

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

      }).ToList(); 
+1

这是不优选的......我会改变函数签名去到'IEnumerable',除非我必须得到'List' –

+0

这实际上是首选,当你想确保结果是物化的,尽管OP没有说明。 –

相关问题