开发者

nhibernate custom collection handling

开发者 https://www.devze.com 2022-12-18 06:37 出处:网络
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 tha

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 perspe开发者_StackOverflow社区ctive, 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>


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>.

0

精彩评论

暂无评论...
验证码 换一张
取 消