无法将查询结果作为特定类型返回

本文关键字:类型 返回 查询 结果 | 更新日期: 2023-09-27 18:37:01

我在下面的GetStudentById方法中收到以下错误消息。"无法将 System.linq.iqueryable 转换为目标类型 system.collections.generic.list"

Que:为什么我不能将我的结果作为学生Dto列表返回

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返回IQueryable<T>,而不是List<T>IQueryable<T>不能自动转换为List<T>

在您的示例中,如果您确实要返回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 语法更具可读性。

但这种方式并不是真正的最佳实践,因为它不支持延迟执行。与其返回List<T>,不如直接返回IQueryable<T>IEnumerable<T>

从 MSDN:

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

这就是为什么可以使用IEnumerable<T>

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

返回 IEnumerable vs. IQueryable