2015-01-11 30 views
0

我在下面的GetStudentById方法中收到了以下错误消息。 “不能转换system.linq.iqueryable为目标类型system.collections.generic.list”无法将查询结果作为特定类型返回

阙:为什么不能我回到我的结果作为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() 
+1

请张贴*确切*错误消息。现在看来,Cuong Le的答案是你能想到的最多的。 –

+0

我做到了。不能将system.linq.iqueryable转换为目标类型system.collections.generic.list – user2320476

+0

不知道你用什么来编写C#代码,但微软的C#编译器/ VS提供了更详细的错误,包括类型 - 例如“ ..IQueryable <...> System.Collection.Generic.List ...“ –

回答

2

主要原因是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语法更具可读性。

但是这种方式并不是最好的做法,因为它不支持延迟执行。您应该直接返回IQueryable<T>IEnumerable<T>而不是返回List<T>

MSDN

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

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

有一件事你也应该从这样的回答你的决定应该使用哪些注意IQueryable<T>IEnumerable<T>之间的区别:

Returning IEnumerable<T> vs. IQueryable<T>

+0

谢谢。我只是尝试了你发送的代码,但它不起作用。我仍然得到db.Students相同的错误消息 – user2320476

+0

回报(从C 选择新StudentDto { 姓= c.FirstName, 姓氏= c.LastName, 部= c.Department, EmailAddress的= c.EmailAddress })。ToList() – user2320476

+0

@ user2320476:你说得对,我编辑了我的答案,因为从你的方法返回StudentDto,而不是Student –