Jimit
Jimit

Reputation: 765

NHibernate requires events to be virtual?

I'm attempting to map an entity hierarchy using NHibernate almost all of which have events. When attempting to build a session factory however, I get error messages similar to the following:

Core.Domain.Entities.Delivery: method remove_Scheduled should be virtual

Delivery is an entity in my domain model with an event called Scheduled. Since events cannot be declared virtual I'm at a loss as to how to proceed here. Why would NHibernate need events to be virtual?

Upvotes: 2

Views: 1102

Answers (3)

Theo de Roo
Theo de Roo

Reputation:

I have experienced the same problem with implementing INotifyPropertyChanged on my lazy loaded objects. The problem is that you actually deal with two different .NET instances so that when you fire the NPC event in your real instance you will not receive it from any reference to the proxy. Making it virtual allows the proxy to 'forward' this event. Unfortunately defining events as virtual/overridable is not possible in VB.NET (2005) and hence we had to introduce a C# project with a base class implementing only these virtual events just to get around the VB issue. see also https://forum.hibernate.org/viewtopic.php?f=25&t=990162&start=0

If there are other ways I would be keen to know myself since our method makes proxies a bit less transparant than they should be. Also in the area of auto reconnecting the session when lazy loaded objects need to be initialized seem a bit of a pain.

Regards, Theo

Upvotes: 1

Daniel Brückner
Daniel Brückner

Reputation: 59655

Public members must be declared virtual if you use lazy loading because NHibernate will create proxy objects for your entities at runtime. So do not use lazy loading or just declare the event as virtual - that is not so common, but it is possible.

NHibernate creates proxy classes for all lazy loaded entities and uses them where an entity is referenced but not yet loaded. Accessing this proxy triggers loading the real entity from the database. This approach requires to inherit from your entity class at runtime and override the public members hence this members to be virtual.

And there is another solution. You can add proxy="ISomeInterface" to the class declaration. Then you do not need virtual members while proxys just implement the given interface.

Upvotes: 2

Frederik Gheysels
Frederik Gheysels

Reputation: 56934

how does your mapping look like ? Did you map an event ?

I haven't encountered this issue before, but, then again, I always specify the 'lazy=false' attribute on my class mapping, so that my properties don't have to be declared as virtual. (Since i do not like to declare properties as virtual, if my business model doesnt requires this)

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

Upvotes: 0

Related Questions