Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot implicitly convert type in LINQ

I was about to build a DTO for list of the 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 anyone explain why?

like image 391
tamikoon Avatar asked Nov 14 '13 23:11

tamikoon


2 Answers

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

           }).ToList();
like image 200
smartcaveman Avatar answered Oct 18 '22 19:10

smartcaveman


You method's return type is ICollection<T> but the query returns an IEnumerable<T> (or an IQueryable<T>). Most likely you don't need an ICollection<T> anyway, and if you did, what would you expect that collection to do? It couldn't be used to manipulate the database. If all you're doing is querying the database, then change the return type of your 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

           };
}
like image 40
p.s.w.g Avatar answered Oct 18 '22 17:10

p.s.w.g