我的对象模型中有一个多级依赖链:
组织具有以下子关系:
Organization
.CompetitionGroups
.CompetitionGroups.Venues
.CompetitionGroups.Competitions
.Divisions.Games
.Divisions.Games.Participants
.Divisions.Games.Participants.GameSegments
.Divisions.SubDivisions...
.Divisions
.Teams
.Teams.Players
.Teams.Participants
.Teams.Participants.GameSegments
.VenueDates
这只是对对象模型的一瞥,但重点是关系和列表的复杂性。
考虑到完成工作单元的要求,我无法真正了解什么是分解我的存储库接口(interface)的最佳方式。
例如,要创建一个游戏,您需要一个 field 日期和两个参与者。这是否意味着 GamesController 应该需要 IGameRepository、IVenueDateRepository 和 IParticipant 存储库?是否应该将它们整合到一个存储库中?
另外,在消费情况下呢?例如,要显示单个团队的日程安排,您需要该团队的所有参与者、该参与者的所有游戏以及该参与者的所有 GameSegment。如果将这些因素考虑到单独的存储库中,我看不出如何进行高效查询。
这是否意味着您有专门针对不同案例的存储库?例如:
public interface IScheduleRepository {
public ICollection<Game> GetScheduleForTeam(Team team);
// More consumption methods
}
public class ScheduleRepositry : IScheduleRepository {
public ScheduleRepository (ModelContext context) {
// Do stuff with context
}
public ICollection<Game> GetScheduleForTeam(Team team) {
return (
from p in context.Participants
where ((p.Game.VenueDate != null) &&
(p.TeamId == team.Id))
orderby p.Game.VenueDate.StartTime
select p.Game).ToList();
}
// more consumption methods
}
public interface IGameRepository {
public void AddGame(Game game);
// More crud methods
}
// Not showing games repository
public class GamesController : Controller {
public GamesController (IGameRepository gamesRepo,
IVenueDateRepository venueDateRepo,
IParticipantRepository participantRepo) {
// do stuff with repos here
}
[HttpPost]
public ActionResult AddGame(Game game) {
// Skipping validation logic
// this?
VenueDate = venueDateRepo.Add(game.VenueDate);
foreach (Participant p in Game.Participants)
{
participantRepo.Add(p);
}
Game = gamesRepo.AddGame(game);
// or this?
// how would the game repo know to persist
// the children elements? is that tight coupling?
Game = gamesRepo.AddGame(game);
}
// more consumption methods
}
我的问题是,我还不明白基于连接的对象模型,您的存储库在多大程度上是有意义的。我很想在这里得到一些建议。
最佳答案
您需要定义您的 aggregate roots和边界,然后围绕根设计您的存储库。
在 this book 中有一个很好的(简短的)章节。 (注册后免费)
至于做一个工作单元,我通常把它作为服务层的一个功能。因此 Controller 具有对服务的引用,服务处理存储库、实体、工作单元等之间的编排。
关于asp.net - MVC : How to factor Repository Interfaces based on multi-level object model,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4999105/