2

I'm using the repository pattern. I'm building up all my objects and I have come to the point where I have an object on a one-to-many relationship.

What im wondering is whether its better to do...

myAssocFile.BlogId = myBlogObject.BlogId;
repository.Add(myAssocFile);

or whether its better to do...

myBlogObject.Add(myAssocFile);

Hope someone can tell me whats better long term?

Exitos
  • 29,230
  • 38
  • 123
  • 178
  • 2
    You should first determine which entities can be considered as are your (aggregate roots)[http://stackoverflow.com/questions/1958621/whats-an-aggregate-root], in order to use them to handle the child objects through their parent repository. – Mahmoud Gamal Apr 12 '12 at 08:34

2 Answers2

1

By using the repository.add methodology you can add logging/error checking/ and additional logic in a recognizable place.

If you did the object.add methodology you would need to create a partial class and overload/override the object.add method to do the same thing. This isn't as clear to all developers as the repository method would be.

So in my opinion you should do all your datastore interaction through your repository (in your case, there are instances where this is not the ideal solution)

gh9
  • 10,169
  • 10
  • 63
  • 96
1

The respository pattern allows you finer control over persistance and construction of your objects. The one point I would add is that the repository pattern is (to me at least) inherently more testable and can withstand dependancy injection without confusion. Also if you think about SOLID object design - does the ability of your parent class to add a child object break the single responsibility rule? Should it care how to add a child? Does it need to know about that extra logic? If that logic needs to change or needs to be tested, it may be easier to do that through a repository.

Ryan Bennett
  • 3,404
  • 19
  • 32