Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate custom collection type

I'm having an entity object called Patient and this entity is having a property called Visits which is of type VisitsCollection.

VisitsCollections is a child class of IList<Visit> but it also adds some custom logic to the collection (like auto ordering, some validation, notifications, etc..).

I need to use the custom collection type as it adds some data to the entities that are added to the collection and performs some other paperwork transparently.

Now I want to map that in NHibernate, so I've created:

<list name="Visits" lazy="true" fetch="select">
    <key foreign-key="PatientId" />
    <index column="Timestamp" />
    <one-to-many class="Visit" not-found="ignore"/>
</list>

I'm getting an exception:

Unable to cast object of type 'NHibernate.Collection.PersistentList' to type '...VisitsCollection'

Whenever I'm accessing the visits property.

I've also tried to map it this way:

<list name="Visits" lazy="true" fetch="select" collection-type="VisitsCollection">
    <key foreign-key="PatientId" />
    <index column="Timestamp" />
    <one-to-many class="Visit" not-found="ignore"/>
</list>

but still, I'm getting this exception:

Custom type does not implement UserCollectionType: .....VisitsCollection

I don't want to inherit my VisitsCollection from any NHibernate type as the collection class is part of a framework that I want it to be DAL-agnostic (as it will be used in many scenarios - not only with a database).

Any ideas on how to map this, preserving the structure of my code?

Thanks in advance.

like image 994
Karim Agha Avatar asked Mar 01 '10 19:03

Karim Agha


1 Answers

I never use custom collection types, mainly because I'm lazy. NHibernate wants you to use a IUserCollectionType I believe, which requires a bit of plumbing.

Rather than that, my first stop would be to look at using extension methods as discussed by Billly McCafferty. But you have code written so...

Alternatively, you could map your collection as a component as discussed here by Colin Jack. This might be easier for your scenario?

Also check this SO thread.

like image 198
tobinharris Avatar answered Nov 10 '22 00:11

tobinharris