tamikoon
tamikoon

Reputation: 727

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?

Upvotes: 5

Views: 5413

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149078

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

           };
}

Upvotes: 4

smartcaveman
smartcaveman

Reputation: 42276

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

           }).ToList();

Upvotes: 7

Related Questions