我想知道使用IRepository模式处理关系数据的推荐方法是什么。
我的数据库具有以下表格,并在括号中带有列名称:
计划(PlanId,名称,CreationDate,
ModifiedDate,ViewId)
区域(AreaId,名称,nTop,nLeft,
nRight,nBottom)
视图(ViewId,nTop,nLeft,nRight,
nBottom)
PlanAreas(PlanId,AreaId)
每个计划可以具有零个或多个Areas但只有一个视图,因此,Plans.ViewId等于Views.ViewId。在PlanAreas中,两列均是相应表的FK。
有时我的应用程序可能希望在这些区域上独立运行,但是通常我将同时加载,保存,删除计划及其所有组成部分(区域,视图)。
我已经开始了....
public interface IPlanRepository
{
IEnumerable<MyModel.Plan> GetAll();
MyModel.Plan GetByName(string sName);
MyModel.Plan GetById(string sId);
void Delete(MyModel.Plan plan);
void SaveOrUpdate(MyModel.Plan plan);
}
public class Plan
{
public Guid Id { get; set; }
public string Name { get; set; }
public DateTime Creation { get; set; }
public DateTime Modified { get; set; }
public MyModel.View View { get; set; }
public IList<MyModel.Area> Areas { get; set; }
}
public class View
{
public Guid Id { get; set; }
public IEnvelope Envelope { get; set; } // encapsulates top, left, bottom, right
}
// etc.
该计划相当复杂,因此实际上会有更多的属性,但这是一个好的开始。所以现在的问题:
我需要IViewRepository和IAreaRepository吗?
在IPlanRepository中实现方法时,我是否需要进行所有工作以获取与计划相关的关系数据(即Areas和View)并返回完全填充的Plan对象?
还是最好有一个更高级别的“聚合器”(因为缺少更好的词),以便在返回计划后填充属性?像这样:
Plan GetPlanById(string sId)
{
Plan myplan = new Plan();
IPlanRepository planrepo = new PlanRepoImpl();
myplan = planrepo.GetById(sId);
IViewRepository viewrepo = new ViewRepoImpl();
myplan.View = viewrepo.GetByPlanId(sId);
return myplan;
}
现在,我正计划使用LINQ-SQL进行数据访问,因为我对此很熟悉,并且可以很快完成。我可能会改用其他方式,但是现在我想保持简单。
最佳答案
您绝对不需要计划子部分的存储库。由于它们在模型内部,因此您可能不需要直接访问它们,如果这样做了,您可能仍然需要参考计划。
既然是这种情况,您可能希望将计划用作主要参考点。然后,使用完整的计划对象,您可以找到任何想要了解的与之相关联的区域和视图的信息。
编辑:
我最近一直在阅读Eric Evans的DDD book,在他的存储库中,他使用了与我上面描述的样式相似的样式。
关于design-patterns - 知识库和关系数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1772212/