Search code examples
nhibernatevirtual

NHibernate: How to disable virtual for class properties?


how exactly I can use public methods (non-virtual) with NHibernate?

I have this code:

public string crewNumber
    {
        get
        {
            return this.crewNumberField;
        }
        set
        {
            this.crewNumberField = value;
        }
    }

Note all my classes, properties, methods and interfaces are auto-generated and I do not want to change them manually.

Above code is producing this error:

The following types may not be used as proxies: ... method get_crewNumber should be 'public/protected virtual'

I see that it shold be possible to use simple public only properties here:

In our example above, we've made the properties and the constructor public - but that's not a requirement for NHibernate - it can use public, protected, internal, or even private properties to persist your data.

How do I turn off this virtual by default?

It's driving me crazy. I am really tempted here to drag one data adapter in visual studio and to end this ridiculous situation once and for all ;-)

Thanks


Solution

  • Specify that dynamic proxies should not be used for that class, by specifying lazy=false on the class-mapping.

    Like this:

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

    This means offcourse that you cannot use dynamic proxies with NHibernate. To be more clear: - when you retrieve an instance of your class, which is able to use dynamic proxies, you'll recieve an 'empty instance'. That is, NHibernate will not fetch the data from the DB yet. You'll get an object who'se Id will be populated, but the other properties are not. Only when you access a property, then NHibernate will load the data from the DB. That's the reason why the properties need to be virtual, because NHibernate will create a subclass of your class internally, and override the properties so that it can achieve this behaviour.

    I always specify 'lazy=false' on my class-mapping, since I don't want to have virtual properties for a reason that is infrastructure-related, instead of 'domain-related'.

    (Note that this has nothing to do with lazy loading of associations; it is still possible to have them lazy loaded when you do not use dynamic proxies).