Baba
Baba

Reputation: 2229

Unable to return query result as a specific type

I have been getting the error message below in the GetStudentById method below. "cannot convert system.linq.iqueryable to target type system.collections.generic.list"

Que: Why cant I return my result as a list of studentDto

public class StudentRepository : IStudentRepository
{
    private TechCollegeEducationEntities db = new TechCollegeEducationEntities();

    public List<StudentDto> GetStudentById(string studentId)
    {
        List<StudentDto> objresult = from c in db.Students
            where c.StudentId == 1
            select c;
        return objresult;

    }

    public List<StudentDto> GetAllStudents()
    {
        throw new NotImplementedException();
    }
} 

Here is my Dto

public class StudentDto
{
    public Int32 StudentId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailAddress { get; set; }
    public string Department { get; set; }
}

I just tried this now and it works for me..

   return (from c in db.Students
                select new StudentDto
                {
                    FirstName = c.FirstName,
                    LastName = c.LastName,
                    Department = c.Department,
                    EmailAddress = c.EmailAddress
                }).ToList()

Upvotes: 0

Views: 208

Answers (1)

cuongle
cuongle

Reputation: 75326

The main reason is LINQ returns IQueryable<T>, not List<T>, and IQueryable<T> cannot automatically convert to List<T>.

In your example if you really want to return List<T>, just call to ToList():

 List<StudentDto> objresult = db.Students.Where(c => c.StudentId == 1)
                                .Select(c => new StudentDto { 
                                       FirstName = c.FirstName, 
                                       LastName = c.LastName, 
                                       Department = c.Department, 
                                       EmailAddress = c.EmailAddress })
                                .ToList();
 return objresult;

Example above using Lambda syntax since I always feel it's more readable than LINQ syntax.

But this way is not really best practice since it does not support deferred execution. Instead of returning List<T>, you should return IQueryable<T> or IEnumerable<T> directly.

From MSDN:

public interface IQueryable<out T> : IEnumerable<T>, IQueryable, IEnumerable

That's why IEnumerable<T> can be used.

One thing you also should notice the difference between IQueryable<T> and IEnumerable<T> from this answer for your decision which should be used:

Returning IEnumerable<T> vs. IQueryable<T>

Upvotes: 2

Related Questions