Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all using IQueryable

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


}

}

like image 203
TMan Avatar asked Feb 20 '12 17:02

TMan


People also ask

Is IQueryable faster than IEnumerable?

IQueryable is faster than IEnumerable. In addition to Munesh Sharma's answer:IEnumerable loads data in-memory and then apply filters to it one by one but IQueryable apply filters all at once and return the result.

Which is better IQueryable or IEnumerable?

So if you working with only in-memory data collection IEnumerable is a good choice but if you want to query data collection which is connected with database `IQueryable is a better choice as it reduces network traffic and uses the power of SQL language.

What is the use of IQueryable?

IQueryable is suitable for querying data from out-memory (like remote database, service) collections. While querying data from a database, IQueryable executes a "select query" on server-side with all filters. IQueryable is beneficial for LINQ to SQL queries.

What inherits from IQueryable?

The IQueryable interface inherits the IEnumerable interface so that if it represents a query, the results of that query can be enumerated. Enumeration causes the expression tree associated with an IQueryable object to be executed.


1 Answers

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

like image 163
Servy Avatar answered Sep 18 '22 15:09

Servy