What is the best way to design repositories for complex objects, assuming use of an ORM such as NHibernate or Entity Framework?
I am creating an app using Entity Framework 4. The app uses complex objects--a Foo
object contains a collection of Bar
objects in a Foo.Bars
property, and so on. In the past, I would have created a FooRepository
, and then a BarRepository
, and I would inject a reference to the BarRepository
into the FooRepository
constructor.
When a query is passed to the FooRepository
, it would call on the BarRepository
as needed to construct the Foo.Bars
property for each Foo
object. And when a Foo
object is pass开发者_如何学Pythoned to the FooRepository
for persistence, the repository would call the BarRepository
to persist the objects in the Foo.Bars
property.
My question is pretty simple: Is that a generally accepted way to set up the repositories? Is there a better approach? Thanks for your help.
In domain-driven design, there is the concept of a "root aggregate" object. The accepted answer to a related question has good information on what it is and how you would use it in your design. I don't know about the Entity Framework but NHibernate does not require the usage pattern you are describing. As long as all the nested objects and their relationships are properly mapped to tables, saving the aggregate root will also save all its child object. The exception is when a nested object has specific business logic that needs to performed as part of its access or persistence. In that case, you would need to pass the "child" repositories so you are not duplicating that business logic.
Repository pattern helps grouping of business transactions among related entities. Meaning if you have two domain objects foo and bar and have a common transactions like GetList(),Update() then a common repository like FoobarReporsitory can be created. You can even abstract that to an interface called IFoobarReporsitory to make application loosely coupled.
精彩评论