Prevent NHibernate mapping property to a proxy

nhibernate

I am searching around for a solution to my problem but all I get is the reasons this does happen as opposed to preventing if from happening.

I have a class, WorkflowActivityInstance which has a collection of WorkflowActivityInstanceTransitions which represents the transitioning of the state of the workflow. The transitions are mapped in a Transitions property fine.

Therefore: WorkflowActivityInstance <– WorkflowActivityInstanceTransition

I would like a view on the object which would give the WorkflowActivityInstance state including its current state, which would simply be the latest WorkflowActivityInstanceTransition without having the user-coder to perform their own sorting and selection on the Transitions property.

Originally, I had:

public virtual IWorkflowActivityInstanceTransition CurrentState
{
    get { return Transitions.OrderBy(q => q.TransitionTimeStamp).LastOrDefault(); }
}

But I just get:

NHibernate.InvalidProxyTypeException:
NHibernate.InvalidProxyTypeException: The following types may not be
used as proxies:
FB.SimpleWorkflow.NHibernate.Model.WorkflowActivityInstance: method
CurrentState should be 'public/protected virtual' or 'protected
internal virtual'.

I tried to be cheeky and convert this to a method:

public IWorkflowActivityInstanceTransition GetCurrentState()
{
    return Transitions.OrderBy(q => q.TransitionTimeStamp).LastOrDefault();
}

But I get a very similar:

NHibernate.InvalidProxyTypeException:
NHibernate.InvalidProxyTypeException: The following types may not be
used as proxies:
FB.SimpleWorkflow.NHibernate.Model.WorkflowActivityInstance: method
GetCurrentState should be 'public/protected virtual' or 'protected
internal virtual'.

I would like to keep the very simple behaviour of CurrentState in my model class, and prevent NHibernate from over-reaching itself and trying to map/proxy this property. It feels that this should just be an attribute on the property I don't want to map …

How can I achieve this?

Best Answer

NHibernate needs to override all public, protected and internal methods, otherwise proxies can't work (it would be possible for your code to access a not yet initialized proxy).

I can't see a reason why your property wouldn't work, but the error is very clear for your method, you miss the virtual keyword.

Related Topic