The key here is that Number is virtual.
AB loads lazily. NHibernate creates a proxy for B , which overrides every virtual property in the class. When you first access one of the non- Id properties, NHibernate will load data from the database to populate the object.
Since this proxy class is a subclass of B , constructor B will be called before the proxy constructor. When constructor B sets the virtual Number property, it calls the Number property, as defined in a proxy subclass that has not yet been initialized.
For a more detailed discussion of constructors and inheritance, see http://www.yoda.arachsys.com/csharp/constructors.html
To fix this, convert any properties that you want to set in the constructor to use support fields instead of automatic properties, and then set this field instead of the property in the constructor.
public class B { public B() { _number = 1; } public virtual int Id { get; private set; } private int _number; public virtual int Number { get { return _number; } set { _number = value; } } }
This is a bit more verbose, but it effectively avoids touching virtual methods or properties in the constructor.
Daniel Schilling
source share