views:

359

answers:

1

Hello

I have a working one to many relationship (NOT bbidirectional) where Resource has a set of many Allocations implented as shown below. The domain needs to do more with the collection of allocations that just manage it with AddAllocation, RemoveAllocation, etc. So from an object perspective, I'd like to put that extra logic that is not persistent related into a different class, AllocationCollection, and make that extra class transparent to NHib.

I'd also like to flesh out the responibilities of the AllocationCollection in a TDD manner, but I'm not sure how to refactor the existing class so NHib still works, mapping wise. How would you do that?

Cheers, Berryl

MODEL

public class Resource {

    public virtual ICollection<Allocation> Allocations
    {
        get { return _allocations ?? (_allocations = new HashSet<Allocation>()); }
        private set { _allocations = value; } // Nhib will use this
    }
}

MAPPING

<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" ...
<class xmlns="urn:nhibernate-mapping-2.2" name="Domain.Model.Resources.Resource, ... table="Resources">
....
<set cascade="all-delete-orphan" name="Allocations">
  <key foreign-key="Allocations_Resource_FK">
    <column name="ResourceId" />
  </key>
  <one-to-many class="Model.Allocations.Allocation, ... />
</set>

+1  A: 

Billy McCafferty has an excellent series of articles on working with custom collections in NHibernate. Personally I no longer use custom collection types. I control collection access from the class containing the collection (i.e. aggregate root) with AddMyType, RemoveMyType, etc., methods. I expose the collection as IEnumerable<MyType>. I've replaced other custom collection accessors with extension methods on IEnumerable<MyType>.

Jamie Ide
Billy's article was exactly what I was looking for! I see [Colin Jack posted](colinjack.blogspot.com/.../nhibernate-mapping-custom-collections.html) a reply where he offers a solution using a custom collection the way I was thinking, but Billy's solution to use extension methods for quering is the least invasive for me right now. Thanks!
Berryl
I agree with you about keeping collection maintenance (add, remove) within the parent class - it's the problem of controlling collection queries within the domain without bloating that parent class and violationg SRP, while staying easy to map that had come up for me; and which your link addresses.
Berryl