Can an Entity access a Repository?

半城伤御伤魂 提交于 2019-12-08 09:38:28

问题


Say I've got two simple entities: User and Review. How bad is it if User calls the Review repository? What is the "clean" way for the User to get its Reviews?

class User
{
    public function getReviews()
    {
        return reviewRepository.findByUser(this);
    }
}

I did have a look at this question, but although they say this is a bad practice, I didn't find an answer there.


回答1:


The clean way in DDD is to have the UserRepository fill the reviews of the User when asking for a User.

class UserRepository
{
  public User GetUserByID(long userId)
  {
    var user = CreateUser();
    user.Reviews = FindReviewsforUser(userID);
    return user;
  }
}

But before you do this, you need to verify that your User Entity in your Domain is also an AggregateRoot! Only AggregateRoots have Repositories. Please take a look at this question to see or get some insights to the problems while desiging aggregateroots.



来源:https://stackoverflow.com/questions/6793047/can-an-entity-access-a-repository

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!