jaffa
jaffa

Reputation: 27350

How to return IList from my repository with ordered queries in LINQ/EF

My repository layer has been working fine, exposing IList<T> for lists of things like GetAll() etc. However, I tried to use OrderBy on one of my LINQ queries. Then I ran into real big problems because the LINQ query cannot be converted to an IList. It wants to return an IOrderedEnumerable.

This is a big problem because I want to keep my repo self contained and NOT expose IQueryable to my services. Why should I change my repo architecture just because of an 'orderby'!

So, despite this I set about converting my repository layer to returning IEnumerable so that I can at least return sorted data. I then ran into more problems because I then needed to convert my data classes to IEnumerable so I can map easily between my view model and data model classes. (This is using AutoMapper).

Then I realised that code-first doesn't like IEnumerable and won't build relationships between tables if not defined using at least an IList (and am also told ICollection??).

So my question is what do I from here? All I want to do is return data to the client (in this case the services), in an ordered fashion without changing return types all the way through my application.

Upvotes: 2

Views: 2063

Answers (2)

Slauma
Slauma

Reputation: 177133

This for instance works and it sorts and returns an IList<T>:

public class Customer
{
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}

public IList<Customer> GetSortedListOfCustomersInCity(string city)
{
    return context.Customers
        .Where(c => c.City == city)
        .OrderBy(c => c.Name)
        .ToList();
}

(I think this is also what Reed Copsey in his answer meant.) I guess, your problem is of another kind, since it is too obvious that this example works. But I couldn't derive from your questions where exactly your issue is. A piece of your not working code is appreciated.

Upvotes: 2

Reed Copsey
Reed Copsey

Reputation: 564373

So my question is what do I from here? All I want to do is return data to the client (in this case the services), in an ordered fashion without changing return types all the way through my application.

When you create your queries, you can always return results.ToList(), which will evaluate them and convert them into an IList<T> for you.

This is, in many cases, advantageous if your query is an IQueryable<T> internally in any case, as it will fully evaluate the query, and prevent issues that can arise if you close your internal data context, then try to enumerate your results.

Upvotes: 1

Related Questions