开发者

Can an Entity access a Repository?

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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜