开发者

How can I ensure that NHibernate creates a IList proxy?

开发者 https://www.devze.com 2022-12-15 20:01 出处:网络
I have a property on my domain object which is exposed as this: public virtual IEnumerable<WorkPost> WorkPosts

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 c开发者_Python百科omes 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 :-))


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消