I am using entity framework with several layers (SOA architecture). I was wondering where it is best to do the ordering of a list or IEnumerable.. would it be on the persistence layer from the repositories ? would it be on the service layer ? or would it be on the presentation layer ? (in controllers)
And why?
While it is certainly possible to sort a list at any layer you have to bear in mind the implications of your choice.
If you are dealing with a large data set, you may want to sort it at database level (for performance reasons). If the data set is small, this is not an issue.
If you perform sorting at the data access layer: you have to either pass sort options to your
GetListmethods or subject all method callers to the same sort order.I view sort order as more of a UI concern and this is best handled in the presentation layer (in your case a controller action).
Update in response to @Rushino comment:
If you are doing pagination at database level then you have no choice but to sort at database level.
Update 2
Here is why you need to sort at database level when you are doing pagination at database level. I will demonstrate with an example:
Given sample data:
3
2
6
4
5
1
Scenario 1: Pagination in the database, sorting in the data layer
When you request page 1 (with page size of 3) database will return:
3
2
6
Data layer will then sort this and return:
2
3
6
Scenario 2: Sorting and pagination both in the database
When you request page 1 (with page size of 3) database will sort first:
1
2
3
4
5
6
Then return page 1 to data layer:
1
2
3
As you can see, the reason for sorting within database when doing pagination is not because of the amount of data. It is because this is the only way to get correct results.