我正在尝试学习N层体系结构和其他一些东西,并且我有一个C#解决方案,其中我有以下几个层:
这个设置看起来正确吗?
它应该很像下面的图像:
当像这样构造时,它看起来非常松散耦合,但是,当我想为一个实体定义一个存储库接口时,就会出现一个问题。问题显然是,为了在接口中使用实体,我必须引用DAL项目.我不知道我哪里出了问题,也不知道该采取什么措施来纠正这个问题。
Core.Repositories中的通用存储库接口:
public interface IRepository<TEntity> where TEntity : class
{
TEntity GetByID(int ID);
IList<TEntity> GetAll();
IList<TEntity> Find(Expression<Func<TEntity, bool>> predicate);
void Add(TEntity entity);
void AddRange(IList<TEntity> entities);
void Update(TEntity entity);
void Remove(TEntity entity);
void RemoveRange(IList<TEntity> entities);
}
将出现上述问题的存储库接口示例(也是在Core.Repositories中):
interface IChildRepository : IRepository<ChildEntity> //In order to use ChildEntity I would have to add a reference to the DAL project
{
IList<Child> GetAllChildren();
}
因此,总之,在这种情况下,我不应该使用存储库模式,或者我可以采取哪些步骤来纠正这个问题?
我看过的关于存储库模式的视频有些不正确,这也是我对模式的理解出现错误和代码中出现错误的原因。我从找到一篇关于存储库模式的非常好的博客文章中找出了问题所在。
我正在创建特定的存储库,但我使用通用存储库作为助手,这样就不需要重复诸如"GetAll“、”添加“或”查找“之类的东西。
在定义我的接口时,我应该这样做:
interface IChildRepository
{
IList<Child> GetAllChildren();
}
然后在我的班上
class ChildRepository : Repository<ChildEntity>, IChildRepository
{
IList<Child> IChildRepository.GetAllChildren() => GetAll().ToModels();
}
显然,我需要重复一些代码,比如"GetAllChildren“、"GetAllParents”等等--我想我只能接受这些了。
发布于 2017-08-13 11:40:33
这是正确的。但是您的存储库应该返回业务对象,而不是数据库“实体”。
次要点。泛型存储库在某种程度上受到了反对。最好是拥有特定的存储库,其方法允许您充分利用数据库来检索所需的确切数据。
简化图
https://softwareengineering.stackexchange.com/questions/355608
复制相似问题