BizApps
BizApps

Reputation: 6130

Best practice in returning select query in linq

I'm a little confused on what among this list below what to use in returning select in linq.

1.IEnumerable 2.List 3.ObjectQuery 4. ConvertLinqtoDataTable

Which do you prefer?

Currently we are used objectquery in returning records.

  public ObjectQuery StationSelectByStationId(int stationid)
    {
        var query = from station in _iiqrEntities.Station
                    where station.StationId == stationid
                    select station;

        return query as ObjectQuery;
    }

I will used your recommendation so that we will standardize our code. Please reference your answer based on my code above.

Thanks in Regards

Upvotes: 1

Views: 859

Answers (3)

Tsabo
Tsabo

Reputation: 844

It depends on the size of data in question and what you will be doing with it. IQueryable does allow to modify the query later, but for large sets of data with complex queries it can result in a big performance drop. In situations like this I prefer to return a list and avoid further headaches, but if you choose to stick with IQueryable you will have to make sure it is evaluated without huge performance hits.

Upvotes: 0

msigman
msigman

Reputation: 4524

You should always return the least restrictive data type you can. It allows the most flexibility in the future and reduces coupling.

Depending on the architecture you've got, this could be an IQueryable<T> if you might want to do LINQ chaining. Or you could return a collection of strongly typed objects such as DTO's as an IEnumerable<T>.

IEnumerable is great for working with sequences that are iterated in-memory, but IQueryable allows for out-of-memory things such as a database or web service.

Upvotes: 0

SLaks
SLaks

Reputation: 887797

You should return an IQueryable<T>.
This allows consumers to add projections to the SQL query without coupling your interface to EF.

Upvotes: 4

Related Questions