Cyberguille
Cyberguille

Reputation: 1602

Query with Repository Pattern

I have the following data base model: enter image description here I use Linq-to-SQL and Design Pattern Repository as describe the fallowing page http://www.remondo.net/repository-pattern-example-csharp/

this is a classes diagram :

enter image description here

I want make a query like this but using instead Repository Design Pattern

ExampleRepositoryDataSet data = new ExampleRepositoryDataSet();
var query = from hotel in data.Hotel
            join category in data.Category on hotel.Category equals category.IdCategory
            join country in data.Country on hotel.Contry equals country.IdContry
            where country.Name == "Cuba"
            orderby hotel.Rating descending
            group new {hotel, category, country} by category.Name;

Upvotes: 2

Views: 3904

Answers (2)

PROMETHEUS
PROMETHEUS

Reputation: 59

you could do something like this:

public class HotelRepository : EFRepository<Hotel>, IHotelRepository
{
     public List<IGrouping<string, Hotel>> GetAllByCountrynameOrderedByCountrynameAndGroupedByCategoryname(string categoryName, string countryName)
     {
          return DbSet
              .Where(hotel => hotel.Country.Name.Equals(countryName))
              .OrderByDescending(hotel => hotel.Rating)
              .GroupBy(hotel => hotel.Category.Name)
              .ToList();
     }
}

Upvotes: 2

Valentin P.
Valentin P.

Reputation: 1151

  1. Repository hides your ORM (Linq-2-SQL, which is also obsolete, it's better to use EF), that is Repository contains reference to ORM-presented dataset, ExampleRepositoryDataSet as I can see.
  2. Repository is often described in terms of Add, Delete, Edit, ListAll methods, thus its implementation can (and have to) use Linq-2-SQL abilities for query construction. It's what you are doing.
  3. You can populate your Repository with method ListHotelsByCountryNameAndOrder(string countryName, bool isAsc) and implement it in the way you've just written.
  4. If you want to use generic repository (someone tells that it's anti-pattern, but I disagree), your problem becomes more difficult but still stays solvable. Take a look at Specification pattern.
  5. Finally, Query Object Pattern is a bit outdated. Today .NET expressions seems to be good alternative. For simple filtering you may populate your repository with method IEnumerable<T> ListAll(Expression<Func<T, bool>> filter) and use it like myRepo.ListAll(t => t.Name == "Cuba"). For complex queries it's a better way to add new method (3.) or use Specification (4.)
  6. Don't return IQueryable from repository. Always call .ToList() or another non-lazy operation to load data.

Upvotes: 1

Related Questions