如何使用IQueryable选择全部内容

8
使用MVC3,我有一个学生仓库(在一个项目中)和一个StudentService(在另一个项目中)。在服务中,我想创建一个函数,该函数返回数据库表中的所有学生。这对我来说是一种新的做法,所以我有点陌生。在下面的GetAllStudents函数中,我应该如何更改语法以选择全部。
在仓库中:
      namespace SpeakOut.Data
{
   public class StudentRepository
{
    SpeakOutDataContext context;
    private Table<StudentEntity> table;
    public StudentRepository()
    {
        context = new SpeakOutDataContext();
        table = context.GetTable<StudentEntity>();
    }


    public IQueryable<Student> Select()
    {
        return table.Select(x => new Student
                                {
                                    WNumber = x.WNumber,
                                    CatalogueYear = x.CatalogueYear,
                                    Standing = x.Standing
                                });
    }
}

在服务中:

   namespace SpeakOut.Services
   {
  public class StudentService
 {
    private StudentRepository repository;
    public StudentService()
    {
        repository = new StudentRepository(); 

    }

    public IQueryable<Student> GetAllStudents()
    {
        return repository.Select().All(x => x.FirstName) ; //**This line is where I don't know how I would call all the students**
    }


}

}


1
哦,等等,为什么我不能只说 return repositry.Select() 呢? - TMan
2个回答

4

您甚至不需要仅仅一个空的选择,您可以直接调用.AsQueryable,或者只需将“table”作为IQueryable返回。


2
public IQueryable<Student> GetAllStudents()
{
    return repository.Select();
}

以上代码只是一个简单的传递方法。唯一的好处是将存储库隐藏在服务后面,并可能通过给它一个更好的名称来实现。

此时还没有检索到任何数据。只有在使用 .ToList() 时,例如当使用 IQuerable 时,才会延迟收集数据。保留为 IQueryable 的好处是可以在代码中进一步添加其他过滤器和排序顺序。这些添加将由 LINQ 提供程序使用。


哈哈,是的,我在那个问题上想太多了...我真是个笨蛋。谢谢! - TMan
编译器错误 CS1501:方法 'Select' 没有重载接受 '0' 个参数。 - HackSlash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接