从我的存储库中运行2个方法在同一个控制器ActionResult中运行是否正确?

时间:2010-10-23 19:58:03

标签: c# asp.net-mvc linq repository-pattern viewmodel

我正在使用ASP.NET 4.0 MVC和C#创建一个商店,并且对它很新。

我来创建View页面,显示特定类别中的产品。

在特定类别页面上,我希望拥有产品列表,并且还希望从数据库中获取相关描述的类别名称。

目前,我这样做的方法是在我的存储库中有两个方法:

  1. 使用字符串
  2. 检索特定类别的产品列表
  3. 使用字符串
  4. 检索特定类别

    然后我在一个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>
    

2 个答案:

答案 0 :(得分:0)

您可能看起来不需要单独获取Category对象,因为您可以从其中一个项引用它。但是,我认为像你这样做可能会很好,因为,例如,你的方法将涵盖目前某个类别中没有任何项目的情况,无论出于何种原因。

答案 1 :(得分:0)

存储库的目的是将数据访问层与业务逻辑分离。当您选择通过类别实体检索产品时,您依赖于延迟加载,这是实体框架的实现细节。如果你愿意的话后来决定切换到不同的数据访问层(例如手工创建的查询),可能就是你不再拥有这个设施了。

第二个问题是,当您将大量功能放入单个存储库方法时,不清楚此方法的责任是什么。正如@Andrew Barber所描述的那样,是的,你会得到很多小方法。然后可以将它们组合以产生有用的功能。当您选择创建更大的方法以返回更多结果时,您会遇到另一个问题。当返回的方法例如三个或四个数据集,你得到的问题是,当你只需要这些数据集中的两个或两个时,你要么创建一个新方法,它比原始方法更少,或者你要运行四个查询其中一两个就够了。

存储库的小方法旨在在更大的整体中编写时产生有意义的结果。许多方法不一定是个问题。你的代码看起来很好:)。