实体可以访问存储库吗? [英] Can an Entity access a Repository?

查看:80
本文介绍了实体可以访问存储库吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说,我有两个简单的实体:用户"和评论".如果用户调用评论"存储库有多严重?用户获得评论的干净"方式是什么?

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.

推荐答案

在DDD中,干净的方法是让UserRepository在询问用户时填充用户的评论.

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;
  }
}

但是在执行此操作之前,您需要验证您域中的用户实体也是AggregateRoot!只有AggregateRoots有存储库.请查看此问题,以查看或了解有关问题的信息在设计aggregateroots时.

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.

这篇关于实体可以访问存储库吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆