扩展(替代)存储库设计模式?

我正在 ASP.NET MVC 中开发一个项目。我想在应用程序的数据访问层和业务逻辑层之间创建一个抽象层。我一直在使用存储库和工作单元。回顾一下,在此模式中,创建了一个通用存储库和许多特定存储库。我在这个项目中遇到的问题是我需要另一个存储库中某个特定存储库的方法。例如,我有一个产品和子产品存储库。我想在 Product 方法中使用 Subproduct 方法,而不是每次都为 Subproduct 重写 LINQ 查询。有没有办法扩展存储库设计模式的功能,或者我必须使用另一种设计模式?


public class ProductSubcategoryRepository : Repository<ProductSubcategory>, IProductSubcategoryRepository

{

    public ProductSubcategoryRepository(DbContext context) : base(context)

    {

    }


    public IEnumerable<ProductSubcategory> CheckSomeCondition()

    {

        // LINQ to check some condition based on product subcategory

    }

}


public class ProductCategoryRepository : Repository<ProductCategory>, IProductCategoryRepository

{

    public ProductCategoryRepository(DbContext context) : base(context)

    {


    }


    public IEnumerable<ProductCategory> GetProductCategoriesBeforeDate()

    {

        // Repeated LINQ to check some condition based on product subcategory 

        // (I am looking for a way to call the same method of ProductSubCategory calss)


        // LINQ To return List of product category if the previous query is true

    }

}


精慕HU
浏览 172回答 2
2回答

慕森王

你已经在你的问题中说过你有业务逻辑层。那是管理这些东西的最佳场所。因此,您不会在另一个存储库中调用一个存储库。相反,您可以通过 BLL 的一种方法调用两个存储库来实现目标。希望您的 UoW 暴露于 BLL。这样,在相同的 UoW 范围内,您可以执行这两个操作。这不仅限于Get记录。这可以进一步扩展到Get-&nbsp;Modify-Update或其他任何内容。我不确定你是做什么的CheckSomeCondition。它只是一个 Predicate 就可以了。如果它是某些业务逻辑的一部分,更好的方法是如上所述将其转移到 BLL。

慕村9548890

最直接的方法是在其构造函数ProductCategoryRepository中创建一个实例:ProductSubcategoryRepositorypublic class ProductCategoryRepository : Repository<ProductCategory>, IProductCategoryRepository{&nbsp; &nbsp; private ProductSubcategoryRepository subRepo;&nbsp; &nbsp; public ProductCategoryRepository(DbContext context) : base(context)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; subRepo = new ProductSubcategoryRepository(context);&nbsp; &nbsp; }&nbsp; &nbsp; public IEnumerable<ProductCategory> GetProductCategoriesBeforeDate()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // call subRepo&nbsp; &nbsp; }}如果你已经有一个ProductSubcategoryRepository你可以注入它的实例:public ProductCategoryRepository(DbContext context, ProductSubcategoryRepository subRepo) : base(context){&nbsp; &nbsp; this.subRepo = subRepo;}
打开App,查看更多内容
随时随地看视频慕课网APP