Cannot implicitly convert type to LINQ

I was going to create a DTO for a list of data.

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

However, when I use this, I get the following error:

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

Can someone explain why?

+4
source share
2 answers

The type of the method to return ICollection<T>, but the request returns IEnumerable<T>(or IQueryable<T>). Most likely, you still do not need ICollection<T>, and if so, what do you expect from this collection? It cannot be used to manage the database. If all you do is query the database, change the type of the returned method to 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

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

           }).ToList();
+5
source

All Articles