2010-10-23 42 views
2

我正在用ASP.NET 4.0 MVC和C#創建一個商店,而且對它來說相當新穎。從我的存儲庫中運行2個方法的ActionResult是否正確?

我已經開始創建顯示某個類別內的產品的View頁面。

在特定的分類頁面上我想要產品列表,並且還希望分類名稱及其從數據庫中取得的相關描述。

目前,我已經做到了這一點的辦法是在我的庫兩種方法:

  1. 檢索的產品列表與字符串特定類別
  2. 用字符串檢索特定類別

然後我在一個ActionResult中使用這兩個,然後將它們傳遞給視圖。

有沒有一種方法可以從1方法調用數據庫中檢索產品列表和類別名稱,描述等等,或者我是否可以正確地完成它?

感謝您提前提供任何幫助。

我的代碼如下:

StoreRepository

public class StoreRepository : topsports.Models.IStoreRepository 
{ 
    private topsportsEntities db = new topsportsEntities(); 

    public IQueryable<Product> FindProductsByCategory(string c) 
    { 
     var products = from p in db.Products 
         where p.Category.Name == c 
         select p; 

     return products; 
    } 

    public Category FindCategory(string c) 
    { 
     return db.Categories.SingleOrDefault(cg => cg.Name == c); 

    } 
} 

IStoreRepository

public interface IStoreRepository 
{ 
    IQueryable<Product> FindProductsByCategory(string c); 
    Category FindCategory(string c); 

} 

StoreController

public class StoreController : Controller 
{ 
    IStoreRepository storeRepository; 

    public StoreController() 
     : this(new StoreRepository()) 
    { 
    } 
    public StoreController(IStoreRepository repository) 
    { 
     storeRepository = repository; 
    } 

    public ActionResult Index(string c) 
    { 
     var category = storeRepository.FindCategory(c); 

     var products = storeRepository.FindProductsByCategory(c).ToList(); 

     var viewModel = new StoreViewModel 
     { 
      Products = products, 
      Category = category 

     }; 

     return View(viewModel); 
    } 
} 

StoreViewModel

public class StoreViewModel 
{ 
    public List<Product> Products { get; set; } 
    public Category Category { get; set; } 

} 

Category.aspx

<h2><%: Model.Category.Name %></h2> 

<p><%: Model.Category.Description %></p> 


<ul> 
    <% foreach (var item in Model.Products) { %> 
     <li> 
      <%: item.Name %>, 
      <strong><%: item.Description %></strong> 
     </li> 
    <%} %> 
</ul> 

回答

0

存儲庫的目的是將您的數據訪問層與業務邏輯分離。當您選擇通過類別實體檢索產品時,您將依賴於延遲加載,這是實體框架的實現細節。當你要例如稍後決定切換到不同的數據訪問層(手工創建查詢例如),則可能是您不再擁有此設施。

第二個問題是,當您將很多功能放入單個存儲庫方法中時,就不清楚此方法的責任是什麼。正如@Andrew Barber所描述的,是的,你會得到很多小方法。這些可以結合起來產生有用的功能。當你選擇創建返回更多結果的更大的方法時,你會遇到另一個問題。當返回例如三個或四個數據集,您會遇到以下問題:當您僅需要這些數據集中的兩個數據集中的兩個數據集時,您要麼創建一個與原始數據集相比更少的新方法,要麼運行四個查詢一兩個就足夠了。

存儲庫的小方法是爲了在整體構成時產生有意義的結果。許多方法不一定是問題。你的代碼看起來很好:)。

+0

感謝您對我的問題的詳細回覆,爲我解決了一些問題。 – user485168 2010-10-24 09:14:30

0

這似乎是你不需要單獨獲得Category對象,因爲你可以從一個引用它的項目。不過,我認爲像你這樣做可能是件好事,例如,你的方法會覆蓋目前類別中沒有任何項目的情況,無論出於何種原因。

相關問題