不能在LINQ中隐式转换类型

tam*_*oon 4 c# linq dto asp.net-mvc-4

我正打算为数据列表构建一个DTO.

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

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

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?)
Run Code Online (Sandbox Code Playgroud)

有谁能解释为什么?

sma*_*man 5

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

           }).ToList();
Run Code Online (Sandbox Code Playgroud)


p.s*_*w.g 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

           };
}
Run Code Online (Sandbox Code Playgroud)