问题
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