2

simple question for real gurus. I lost a lot of time figuring how to map collection in nhib. mapping by code and I now I have question, why my mapping work with collection of type IList and not with List?

Here's the code

public class Account {
    private IList<Term> Terms; // When I use List it does not work
    public Account()
    {
       Terms = new List<Terms>(); 
    }
    public virtual IList<Term> Terms // When I use List it does not work
    {
       get { return _Terms; }
       set 
       { if (_Terms == value) return;
           _Terms = value;
       }
    }
}

AccountMap.cs (One account have many terms)

Bag(x => x.Terms,
         m =>{},
         x => x.OneToMany()
);
user1765862
  • 13,635
  • 28
  • 115
  • 220
  • Related: http://stackoverflow.com/questions/17170/when-to-use-ilist-and-when-to-use-list – Oded Jan 12 '13 at 17:58
  • How does it not work? I think NHibernate requires you to use interface types for mapped collections you want to lazily load since it needs to proxy them at runtime. – Lee Jan 12 '13 at 17:58

2 Answers2

2

Documentation says: 6.1. Persistent Collections:

NHibernate requires that persistent collection-valued fields be declared as an interface type

And the list of supported interfaces:

The actual interface might be Iesi.Collections.ISet, System.Collections.ICollection, System.Collections.IList, System.Collections.IDictionary, System.Collections.Generic.ICollection<T>, System.Collections.Generic.IList<T>, System.Collections.Generic.IDictionary<K, V>, Iesi.Collections.Generic.ISet<T>

or ... anything you like! (Where "anything you like" means you will have to write an implementation of NHibernate.UserType.IUserCollectionType.)

Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
0

NHibernate works with IList and IList<T> (and some other collection interface types) because internally NHibernate uses its own implementations of those interfaces in order to track changes etc.

Exposing collection interface types instead of concrete collection implementations in your domain classes is also sound from a object design perspective.

Oskar Berggren
  • 5,583
  • 1
  • 19
  • 36