Mapping custom lists with Fluent NHibernate

NHibernate supports mapping to a few collection types by default, like IList of ISet, but they must be interfaces. To support other types of collections, including concrete classes, you should implement IUserCollectionType inteface. Being lazy as I am, however, I found a way to map custom collections as components using Fluent NHibernate. Here’s how it looks like:

Component(x => x.ChildUsers,
					  m => m.HasMany<User>(Reveal.Member<BindingList<User>>("innerList")).KeyColumn("parent_user_id").Access.Field());

The custom collection in this case is BindingList(T), a generic implementation of IBindingList interface for my own use. The trick is that it has to have a innerList field of any supported NHibernate collection type.

There are other variations of such mappings on the net, but other didn’t work for me with SQLite, throwing exceptions about generated DDL for tables.

Advertisements

2 thoughts on “Mapping custom lists with Fluent NHibernate

  1. This doesn’t seem to work with lazy loading – have you encountered the same issue?

    1. Didn’t encounter this, but it seems logical. Lazy loading requires virtual properties/methods, so a proxy type for the entity can be generated at runtime. Since fields cannot be virtual, lazy loading is probably not allowed. The custom collection we’re binding is probably also incapable of lazy loading behavior – NHibernate uses special collection implementations to do lazy loading, hence the need to use collections as interfaces, not concrete classes.

      I hope it is clear enough now 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s