views:

59

answers:

3

Why are the entity class methods declared as public virtual, when the class is to be mapped with a table using NHibernate.

Is the answer that NHibernate will be able to override these methods at runtime?

+3  A: 

Yes. NHibernate will return a proxy to your object. In the simplest case, this will be fully uninitialized, and just aware of its type and id. Thus NHibernate will need to intercept method calls on the object and initialize it before the body of the message is called.

David M
+1  A: 

NHibernate needs properties to be virtual in order to support lazy-loading via proxy classes.

Kevin Pang
+2  A: 

NHibernate requires this by default because it generates a proxy for your class, to support lazy loading of the entity (not to be confused with lazy loading of associated entities or collections). When loading an entity from the DB using NHibernate's 'ISession.Load' method, NHibernate will return a proxy for that entity, which means that it returns an empty entity, where only the primary key (identifier) is set. The values of the other properties are only retrieved once you actually read a property.

However, you can disable this behaviour. In your NHibernate mapping, you can specify that no dynamic proxies should be used by NHibernate for an entity. This is fairly simple to do, you just have to specify lazy="false" on the class - mapping:

MyEntity.hbm.xml:

<class name="MyEntity" table="MyTable" lazy="false">
</class>

By doing this, you do not have to declare virtual properties or methods. I mostly do it this way, since I don't wan't to declare properties or methods as virtual, if my domain model doesn't require this. I can live with the -imho- minimal performance hit of not using dynamic proxies.

Frederik Gheysels