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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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:
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.