使用SQL后端时的存储库模式和项删除

时间:2009-02-17 14:06:58

标签: c# domain-driven-design repository-pattern

所以假设我有一个名为Post的类,其中包含一个IList

我发现,当我要求我的存储库更新我的帖子时,可以很容易地处理向列表中添加注释,它可以查看哪些注释是新的,并将所需的信息发送到我的数据层,但是当评论被删除?你怎么处理这个?

您是否会撤回注释列表以检查当前更改的集合中哪些不再存在?

或连接事件以跟踪它?

或其他完全不同的东西?

仅供参考,我在C#中这样做,不能使用O / R Mapper。我必须使用存储过程来检索数据集并手动映射我的对象。我可能对存储库模式的理解是错误的,但我使用它来调解数据层,从请求数据,添加数据等,并将我的数据集数据映射到对象并返回对象。因此,如果您愿意,请随时详细说明如何使用Repository模式。

1 个答案:

答案 0 :(得分:0)

如果我理解你在尝试什么,那么你正在向有问题的IList添加一个Comment(),它附在Post()上。在你的Post()中,你正在寻找IList中的任何新的Comment()并保存它们。让Post()对象控制其子对象(例如Comment()s)确实可以实现DDD。

我自己仍然对这些模式不熟悉;但就个人而言,我倾向于任何具有元数据的实体,我将其视为自己的实体模型;因此,我为每个实体模型创建了自己的repostiory。

Post()
PostRepository : IPostRepository

Comment()
CommentRepository : ICommentRepository

现在,有一个IList Post.Comments,我认为允许你执行Post.Comments.Add()违反了 Demeter法

我相信你的问题的解决方案不会添加到IList,而是在Post()上创建方法来处理与该Post实例相关的注释:

Post.AddComment()
Post.FetchComments()
Post.DeleteComments(IList<Comment> comments) 

然后在你的Post()对象中,你将连接你的ICommentRepository(很可能是ServiceLocator,或者我更喜欢Castle Windsor)并处理它们的添加和删除。

ICommentRepository.AddByPostID()
ICommentRepository.FetchByPostID()
ICommentRepository.Remove(int commentID)

同样,我仍然是DDD模式的新手;但是,我相信这会让关注分离保持有效,并通过将其置于Post()关注的“仅处理与此Post对象相关的注释上的操作”来掩盖基础逻辑。

完整的Post()类将是这样的:

private ICommentRepository _commentRepo;

public class Post
{
  public Post(ICommentRepository commentRepo)
  {
    // Or you can remove this forced-injection and use a 
    // "Service Locator" to wire it up internall.
    _commentRepo = commentRepo;
  }

  public int PostID { get; set; }

  public void DeleteComments(IList<Comment> comments)
  {
    // put your logic here to "lookup what has been deleted"
    // and then call ICommentRepository.Delete() in the loop.

    _commentRepo.Remove(commentID);
  }
}

如果其他人有意见或变更,请发表评论。