简体   繁体   English

如何使用IQueryable选择所有

[英]How to select all using IQueryable

Using MVC3, I have a Student Repository (in a project) and a StudentService (in another project). 使用MVC3,我有一个Student Repository(在一个项目中)和一个StudentService(在另一个项目中)。 In the service I want to create a function that returns all of the students that are in the db table. 在服务中,我想创建一个函数,返回db表中的所有学生。 This is a new way of doing things for me so I'm a bit new. 这是一种为我做事的新方式,所以我有点新鲜。 in the GetAllStudents Function below, How could I change the syntax to select all. 在下面的GetAllStudents函数中,我如何更改语法以选择所有。

In Repository: 在存储库中:

      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
                                });
    }
}

} }

In Services: 在服务中:

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


}

} }

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

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

The code above just a pass-through method. 上面的代码只是一个传递方法。 The only benefit is hiding the repository behind the service and perhaps by giving it a better name. 唯一的好处是将存储库隐藏在服务后面,并且可能通过给它一个更好的名称。

At this point no data has been retrieved. 此时尚未检索到任何数据。 The collection of data is deferred until IQuerable is being used for example when .ToList() is called. 延迟数据集合,直到使用IQuerable ,例如调用.ToList()时。 The benefit of leaving it as IQuerablye is that additional filters and sort orders can be added by code further down the line. 将其保留为IQuerablye是可以通过代码进一步添加额外的过滤器和排序顺序。 These additions will be used by the LINQ provider. 这些添加内容将由LINQ提供程序使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM