views:

35

answers:

1

I have a property on my domain object which is exposed as this:

    public virtual IEnumerable<WorkPost> WorkPosts
    {
        get { return sheetPosts; }
        private set
        {
            Guard.AssertAssignableFrom(value, typeof (IList<WorkPost>));
            sheetPosts = value as IList<WorkPost>;
        }
    }

The internal representation is an IList<WorkPost> and as you can see, the assigned value (which is a lazy loading proxy that comes from NHibernate) is then cast to the correct type. This implementation gave me a bad taste in my mouth because it depends on the internal representation of NHibernate proxies. To make sure that NHibernate generates the proxy as a List I created the fluent mapping for the property with an AsList() declaration:

        HasMany(sheet => sheet.WorkPosts).KeyColumn("sheetId").AsList();

But this gave me a bit more than requested, because the list semantics implies sorting which again adds some extra fields to the database model and also some extra queries (due to updating of the sort field when committing), so the above "AsList" has to go.

How can I control what type of interfaces NHibernate should return when generating the proxy? (note: changing the IEnumerable return type on the property is not the answer I'm looking for :-))

+1  A: 

If you don't want sorting semantics you should use a set or a bag, depending on whether you allow duplicate elements or not. Here's the documentation on collections for more info.

NHibernate is very strict on the semantics of collections:

  • a list (persists IList) is an ordered collection that allows duplicates and can be indexed with integers;
  • a map (persists IDictionary) is an unordered collection that is indexed with uniques keys of a given type;
  • a set (persists ISet from Iesi.Collections, probably will use the ISet that comes with the version 4 of the framework) is an unordered collection that does not allow duplicates.
  • a bag (persists ICollection or IList but provides no guarantees for indexing) is an unordered collection that allows duplicates.
Martinho Fernandes