سؤال

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?

هل كانت مفيدة؟

المحلول 2

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

           };
}

نصائح أخرى

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

           }).ToList();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top