【问题标题】:Entity Framework Repository Pattern - Database Catalogs实体框架存储库模式 - 数据库目录
【发布时间】:2014-06-04 19:40:00
【问题描述】:

我已经在我的 ASP.NET Web API 项目中实现了存储库模式和工作单元。

效果很好。现在向我提出了一个关于存储库的问题,该存储库可以处理我的应用程序中有关设置目录的所有信息。

现在我必须在我的工作单元中创建所有引用 EF 实体的公共存储库,如下所示:

public IRepository<Document> Document { get { return GetStandardRepo<Document>(); } }

Document 是一个 EF 实体。 IRepository 实现了以下方法:

public interface IRepository<T> where T : class
    {
        IQueryable<T> GetAll();
        IQueryable<T> GetAllReadOnly();
        T GetById(int id);
        void Add(T entity);
        void Update(T entity);
        void Delete(T entity);
        void Delete(int id);
    }

我的数据库中有大约 20 个用于安装目录的表,所以如果我遵循这种模式,我将不得不创建 20 个:

public IRepository<SetupEmployeeType> Document { get { return GetStandardRepo<SetupEmployeeType>(); } }
public IRepository<SetupMaritalStatus> Document { get { return GetStandardRepo<SetupMaritalStatus>(); } }
public IRepository<SetupRelationshipCode> Document { get { return GetStandardRepo<SetupRelationshipCode>(); } }
public IRepository<SetupLocationType> Document { get { return GetStandardRepo<SetupLocationType>(); } }
.....
.....

我正在考虑的一个解决方案是创建我自己的自定义 IRepository 实现,可能是 IATAlogRepository,如下所示:

 public class CatalogRepository : EFRepository<EF Entity>, ICatalogRepository
        {
            public CatalogRepository (DbContext context) : base(context) { }


            public IEnumerable<SetupEmployeeType> GetEmployeeTypes()
            {
                var catalog = DbContext
                    .Set<SetupEmployeeType>()
                    .ToList();

                return catalog;

            }

public IEnumerable<SetupMaritalStatus> GetMaritalStatus()
            {
                var catalog = DbContext
                    .Set<SetupMaritalStatus>()
                    .ToList();

                return catalog;

            }
        }

我的问题是 CatalogRepository 必须继承自 EFRepositoryT 不仅仅是一个实体,因为我会从不同的方法返回不同的实体.

这是正确的做法吗?

【问题讨论】:

    标签: entity-framework entity-framework-4 repository-pattern unit-of-work


    【解决方案1】:

    是的,不要使用这种反模式(通用存储库包装 DbContext,同时公开 EF 实体)。如果您真的想使用 Repository,请让存储库接口仅返回业务(或查看模型,如果它是查询存储库)对象,切勿返回 IQueryable 或其他暴露 EF 的详细信息或您使用的任何内容。

    只需为您的需求创建一个存储库,忘记通用的东西,它是一种反模式。因此,您的 CatalogRepository 将使用一个 DbContext 来发出所有需要的查询,然后从结果中组装一个视图模型/业务对象并返回它。

    应用程序只会知道 Repo,而不会知道 EF。查询将保留在 DAL 级别(不在您的应用/服务/控制器中),并且您的应用已解耦,关注点分离得到尊重。

    包装 DbContext 的类充其量是无用的(它带来了什么价值?),最坏的情况是一个泄漏的抽象。让您的生活更轻松,如果您想直接使用 EF 实体和 EF,请直接使用 EF。如果您想将应用程序的其余部分与持久性细节(注意我说的是持久性,而不是 rdbms)分离,请正确使用 Repository。但是不要因为你有一个名为repository 的类而自欺欺人你正在使用Repository 模式。您应该确切地知道为什么要使用一种模式以及它给您的情况带来什么好处。如果您不明白为什么,这不是最佳做法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多