无法 return 以特定类型查询结果

Unable to return query result as a specific type

我在下面的 GetStudentById 方法中收到了下面的错误消息。 "cannot convert system.linq.iqueryable to target type system.collections.generic.list"

问题:为什么我不能 return 我的结果作为 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();
    }
} 

这是我的 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; }
}

我刚试过这个,它对我有用..

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

主要原因是LINQ returns IQueryable<T>,不是List<T>,而且IQueryable<T>不能自动转换为List<T>.

在你的例子中,如果你真的想要 return List<T>,只需调用 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;

上面的示例使用了 Lambda 语法,因为我总觉得它比 LINQ 语法更具可读性。

但是这种方式并不是真正的最佳实践,因为它不支持延迟执行。您应该直接 return IQueryable<T>IEnumerable<T> 而不是 returning List<T>

来自 MSDN:

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

这就是 IEnumerable<T> 可以使用的原因。

你还应该注意到这个答案中 IQueryable<T>IEnumerable<T> 之间的区别,以便你决定应该使用哪个:

Returning IEnumerable<T> vs. IQueryable<T>