允许通过互操作进行 CRUD 操作的数据库存储库模式

Repository pattern for database that allows CRUD operations through Interops

我们目前面临的情况是模型实体和数据库逻辑紧密交织在一起,这使得单元测试变得不可能。因此,我决定着手设计存储库模式。我们通过Com交互看到的存储模型的基本结构Root-Children[每个child是另一个Root]。是树状结构。了解了这一点,我们设计的 Repository 是 RootRepository 用于 root 的 CRUD 操作和 RootRepository 内部的 ChildRepository 用于 child 的 CRUD 操作。我们决定 Create 只创建一个实体而不是持久化它,但是更新将仅在没有实体是 key 未在数据库中找到时插入或在找到时更新。读取将按键获取实体。因此,在与 Repository API 交互时,我们决定首先使用 key 获取实体,如果它为 null,则调用 Create basic entity(Repository uses factory),如果需要可以更新它,并使用 update 持久化回 DB .没有 child 可以自己持久化,因为它是一个指向另一个实体的值 object。要持久化 child,我们必须首先持久化 child 引用实体,然后请求根存储库创建 child object 然后可以添加到 parent children 集合和 parent 持久化被调用,因此 children 将与 parent 一起被持久化。

所以,我想知道我们遵循的方法和设计模式是否真的符合标准。据我们所知,这是我们可以使用最少的数据模拟获得单元测试和测试支持的唯一方法。我在网上四处寻找构建存储库的想法,但没有任何帮助。我在这里的大部分问题都将在我们的单元测试中得到解决,但我想知道是否已经存在任何设计模式。在这个早期阶段,很容易迁移到任何存在的标准框架,我希望能从你们那里得到任何指导。

实施下面的代码,您将能够在您的所有实体中重复使用它。

public interface IRepository<T> where T : class
{
    T Find(params object[] id);
    IQueryable<T> Where(Expression<Func<bool, T>> predicate);
    T Add(T entity);
    T Update(T entity);
    void Delete(T entity);
}

public class Repository<T> where T : class
{
    private DbSet<T> dbSet;
    public Repository(ApplicationContext context)
    {
        this.dbSet = context.Set<T>();
    }

    public T Find(params object[] id) { throw new NotImplementedException(); }
    public IQueryable<T> Where(Expression<Func<bool, T>> predicate) { throw new NotImplementedException();}
    public T Add(T entity){ throw new NotImplementedException();}
    public T Update(T entity){ throw new NotImplementedException();}
    public void Delete(T entity){ throw new NotImplementedException();}
}