Hi,
I’m using NHIbernate 2.1.0.4 and VB.NET with Oracle.
The primary key of the database table (called Component) I’m mapping with NHibernate is generated using two values stored in different tables (please do not ask me why… I’m struggling myself to understand the reason why somebody took this decision!).
So I thought to let the application assign the identifier by defining the id generator with class=”assigned”. I then intercept when the class is saved and set its id in the OnSave method of the interceptor.
However I get the following error when I try to flush the session:
identifier of an instance of DataModel.Component was altered from 0 to 166
Here’s the code I’m using:
Mapping
Code:
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly=" DataModel" namespace="DataModel">
<class name="Component" table="Component">
<id name="ComponentId" column="ComponentId" type="Int32" unsaved-value="undefined">
<generator class="assigned" />
</id>
<property name="Description" column="Description" type="string" length="100" not-null ="true"/>
</class>
</hibernate-mapping>
Component class
Code:
Public Class Component
Private _componentId As Integer
Public Overridable Property ComponentId() As Integer
Get
Return _componentId
End Get
Set(ByVal value As Integer)
_componentId = value
End Set
End Property
Private _description As String
Public Overridable Property Description() As String
Get
Return _description
End Get
Set(ByVal value As String)
_description = value
End Set
End Property
Private _objectName As String
Public Overridable ReadOnly Property ObjectName() As String
Get
Return _objectName
End Get
End Property
Public Sub New()
End Sub
Public Sub New(ByVal objectName As String)
_objectName = objectName
End Sub
End Class
Interceptor
Code:
Public Class ComponentInterceptor
Inherits EmptyInterceptor
Public Overrides Function OnSave(ByVal entity As Object, ByVal id As Object, ByVal state() As Object, ByVal propertyNames() As String, ByVal types() As NHibernate.Type.IType) As Boolean
If TypeOf (entity) Is Component Then
CType(entity, Component).ComponentId = CreateNewId
End If
Return MyBase.OnSave(entity, id, state, propertyNames, types)
End Function
End Class
Main function
Code:
Private Function CreateAndSaveSampleEntity() As Object
Dim id As Object
Dim entity As Component = CreateSample()
id = session.Save(entity)
session.Flush()
session.Refresh(entity)
Return id
End Function
Am I missing something very obvious?
Any help will be very appreciated.
Thanks in advance!