如何使用IQueryable选择所有

TMa*_*Man 6 c# entity-framework

使用MVC3,我有一个Student Repository(在一个项目中)和一个StudentService(在另一个项目中).在服务中,我想创建一个函数,返回db表中的所有学生.这是一种为我做事的新方式,所以我有点新鲜.在下面的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
                                });
    }
}
Run Code Online (Sandbox Code Playgroud)

}

在服务中:

   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**
    }


}
Run Code Online (Sandbox Code Playgroud)

}

Ser*_*rvy 5

您甚至不需要一个空白的 Select,您可以只调用 .AsQueryable,或者只是将“table”作为 IQueryable 返回。


Phi*_*rie 3

public IQueryable<Student> GetAllStudents()
{
    return repository.Select();
}
Run Code Online (Sandbox Code Playgroud)

上面的代码只是一个传递方法。唯一的好处是将存储库隐藏在服务后面,也许可以给它一个更好的名称。

此时尚未检索到任何数据。数据的收集被推迟到IQuerable被使用时,例如.ToList()被调用时。保留它的好处IQuerablye是可以通过代码进一步添加额外的过滤器和排序顺序。这些添加内容将由 LINQ 提供程序使用。