How to use IQueryable to select all

c# entity-framework

Question

Using MVC3, I have a Student Repository (in a project) and a StudentService (in another project). In the service I want to create a function that returns all of the students that are in the db table. 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.

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


}

}

1
6
2/20/2012 5:03:28 PM

Accepted Answer

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. The benefit of leaving it as IQuerablye is that additional filters and sort orders can be added by code further down the line. These additions will be used by the LINQ provider.

2
2/20/2012 5:11:08 PM

Popular Answer

You don't even need just a blank Select, you can just call .AsQueryable, or just return 'table' as an IQueryable.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow