2014-09-05 76 views
1

我有以下的數據庫模型: enter image description here 我使用LINQ到SQL和設計模式庫作爲描述休耕頁http://www.remondo.net/repository-pattern-example-csharp/查詢與存儲庫模式

這是一個類圖:

enter image description here

我想做出這樣的查詢,但是改爲使用資源庫設計模式

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; 
+1

與單一實體接入場景打交道時,你正在使用的模式是好的。當你不得不在多個實體之間進行合成時,並非如此。沒有正確的答案,您應該提交您提交的查詢的位置,但處理這些類型問題的編排層將是一個好的開始。您仍然可以使用個人存儲庫訪問編排層內​​的所有酒店,類別和國家/地區數據。祝你好運。 – 2014-09-05 14:38:59

+0

@RobEpstein謝謝你的幫助,然後你建議我添加數據源並使用ExampleRepositoryDataSet對象來查詢。我可以使用查詢對象模式? – Cyberguille 2014-09-05 15:16:49

+0

你的問題是什麼? – 2014-09-05 15:51:32

回答

1

你可以做這樣的事情:

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(); 
    } 
} 
0
  1. Repository隱藏您的ORM(Linq-2-SQL,也是過時的,最好使用EF),即我知道存儲庫包含對ORM提交的數據集的引用ExampleRepositoryDataSet
  2. Repository通常用Add, Delete, Edit, ListAll方法描述,因此它的實現可以(並且必須)使用Linq-2-SQL能力來進行查詢構建。這就是你在做什麼。
  3. 您可以使用方法ListHotelsByCountryNameAndOrder(string countryName, bool isAsc)填充您的Repository,並按照您剛剛編寫的方式實施它。
  4. 如果你想使用generic repository(有人說它是反模式,但我不同意),你的問題變得更加困難,但仍然可以解決。看看Specification模式。
  5. 最後,Query Object Pattern已經過時了。今天.NET表達式似乎是很好的選擇。對於簡單過濾,您可以使用方法IEnumerable<T> ListAll(Expression<Func<T, bool>> filter)填充存儲庫,並使用它,如myRepo.ListAll(t => t.Name == "Cuba")。對於複雜查詢,這是添加新方法(3.)或使用規範(4.)的更好方法。
  6. 不要從存儲庫返回IQueryable。總是請撥打.ToList()或另一個非惰性操作來加載數據。