收录日期:2020/12/05 23:24:59 时间:2010-09-08 12:50:21 标签:nhibernate,collections

Following the technique described here, I was able to populate a domain object that uses custom collections for its children. The relevant property mapping looks like this:

    <component name="Contacts" class="My.CustomList`1[[Domain.Object, DomainAssembly]], MyAssembly">
        <set name="InnerList">
            <key column="PARENT_ID" />
            <one-to-many class="Contact" />
        </set>
    </component>

My custom collection class exposes the InnerList property as an ICollection like so:

    protected System.Collections.ICollection InnerList
    {
        get
        {
            return this;
        }
        set
        {
            Clear();
            foreach (DomainObject o in value)
            {
                Add(o);
            }
        }
    }

This worked like a charm to load data from the database and not have to abandon my rather useful custom collection class.

Then I moved on to try implement saving, and following the advice given in this thread, decided to wrap every call to NHibernate in a transaction.

Now when I commit following my load, NHibernate throws an InvalidCastException: "Unable to cast object of type 'My.CustomList`1[Domain.Object, DomainAssembly]' to type 'Iesi.Collections.ISet'."

Is there a way to make this work the way I expect it to?

EDIT:

Following the lead provided by Raphael, I tried switching to ICollection<T> which gives me a different InvalidCastException when I commit the transaction: Unable to cast object of type 'My.CustomList`1[Domain.Object]' to type 'NHibernate.Collection.IPersistentCollection'.

Change the property to be of type

IList<T>