nhibernate custom collection handling

孤街醉人 提交于 2019-12-20 17:29:54

问题


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:


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



来源:https://stackoverflow.com/questions/2161941/nhibernate-custom-collection-handling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!