views:

326

answers:

1

I have a Question object thats the root of the Question Aggregate. THe question has associated Answer Entities in its aggregate . When a new Answer object is created, the changes will be saved to DB via repository. Can I call a repository method SaveAnswer(Question ID) or must I call a SaveQuestion(QUestionID) and have the Repository determine what changes were made? If the latter, how is this implemented?

Conversely, If I want to load up all the Answers to a particular Question, must I call GetQuestion() and then pull the answers, or can I simply call GetAnswers(questionID).

tia

+6  A: 

Firstly, let me say there are no hard and fast rules here, this is my understanding of DDD and repository access, but it's a fairly subjective area...

So, from a DDD perspective what you might want to do when adding an Answer to an existing Question is something like the following C# style pseudocode:

using(unitOfWork = new UnitOfWork())
{
  var question = _questionRepository.GetQuestion(questionId);
  question.AddAnswer(new Answer("blah"));
  unitOfWork.SaveChanges();
}

Assuming you are using an ORM that handles change tracking and that is configured to cascade child objects back to the database that is all you would need to do (I'm thinking of NHibernate here, but other ORMs can work in a similar way). By adding the Answer to the Question you have told the ORM that you want the Answer to be persisted in the database when the unit of work completes. You typically wouldn't call SaveAnswer(QuestionId) - that's not a very DDD-centric way of approaching things where Answer is in the same aggregate as Question and Question is the aggregate root.

For getting the objects out of the database, typically you would ask the repository for a question object (by id presumably), and then navigate to the Answer from there (via an Answers collection on the Question) - e.g.

var question = _questionRepository.GetQuestion(questionId);
foreach(var answer in question.Answers)
{
  Console.WriteLine(answer.Description); // or do something useful instead!
}

If this seems like a strange way to save or retrieve the Answer object then you might want to re-assess whether Answer does actually belong in the same aggregate, or whether it would be better to break it out of the question aggregate altogether.

Steve Willcock
thats the answer i was hoping not to get :) thanks
zsharp