我对存储库层(数据)和服务层(业务)之间的分离有点困惑。我对复杂的跨表或跨数据库查询有意义。您在存储库中查询行数据。在Business层中,我从Repos获取数据并执行逻辑。
简单的CRUD功能怎么样? 在我的WCF服务的服务方法中(基本上是"终端客户端")我应该只调用业务层,但是每次我都要经过那层,即使是简单的"添加"操作。我应该跳过服务层并直接调用存储库吗?
谢谢,
以下是我的建议: 首先,我将发布我的存储库模式的代码:
通用存储库:
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
protected DbContext Context { get; }
public Repository(DbContext dbContext)
{
Context = dbContext;
}
public TEntity Get(int id)
{
return Context.Set<TEntity>().Find(id);
}
public IEnumerable<TEntity> Get(Func<TEntity, bool> predicate)
{
return Context.Set<TEntity>().Where(predicate);
}
public IEnumerable<TEntity> GetAll()
{
return Context.Set<TEntity>().ToList();
}
public void Add(TEntity entity)
{
Context.Set<TEntity>().Add(entity);
}
public void AddRange(IEnumerable<TEntity> entities)
{
Context.Set<TEntity>().AddRange(entities);
}
public void Remove(TEntity entity)
{
Context.Set<TEntity>().Remove(entity);
}
public void RemoveRange(IEnumerable<TEntity> entities)
{
Context.Set<TEntity>().RemoveRange(entities);
}
}
特定存储库:
public class StudentRepository : Repository<StudentDto>, IStudentRepository
{
public StudentRepository(SchoolContext dbContext)
: base(dbContext)
{
}
public int GetStudentSomething(int studentId)
{
return SchoolContext.Students.Where(m => m.StudentId == studentId);
}
private SchoolContext SchoolContext => Context as SchoolContext;
}
工作单位: Yeees ..我有工作单元抽象,但对于这个问题并不重要。我知道很多人不喜欢EF。但是对于这个特定问题,它并没有改变任何东西。所以这里有UoW:
public class UnitOfWork : IUnitOfWork, IDisposable
{
protected SchoolContext Context { get; }
public IStudentRepository Student { get; }
public UnitOfWork(SchoolContext context)
{
Context = context;
Student = new StudentRepository(Context);
}
public int Complete()
{
return Context.SaveChanges();
}
public void Dispose()
{
Context?.Dispose();
}
}
现在......我的建议。怎么样?
public class StudentService : StudentRepository
{
public StudentService(SchoolContext dbContext) : base(dbContext)
{
}
}
已经有了所有CRUD和其他方法+我仍然可以添加更复杂的逻辑。即使在两个数据库!像这样:
public class StudentService : StudentRepository
{
public StudentService(SchoolContext dbContext, ClubContext dbContext) : base(dbContext)
{
}
public bool foo()
{
// This method can get data from two databases, and calculate results
}
}