I have a customer object with a corresponding table in a SQL Server-database. The object has a property 'Id' which corresponds with the primary key 'customerid' which is an identity column.
When I make a new customer and then push the save button, the following code is executed:
Code:
private void SaveCustomer()
{
try
{
if (_customer.Id == -1)
{
SaveObject(_customer);
}
else
{
UpdateObject(_customer);
}
}
catch (Exception ex)
{
ShowError(ex.Message);
}
}
public void SaveObject(object obj)
{
ITransaction trn = _activeSession.BeginTransaction();
try
{
_activeSession.Save(obj);
trn.Commit();
}
catch (Exception ex)
{
trn.Rollback();
throw ex;
}
}
This works fine, the new customer is saved into the database. But...
When I push the save button again, the Id-property of the customer is still -1 and SaveObject is invoked while this time it shouldn't be. NHibernate comes up with the following error: 'An error occured: null id in entry (don't flush the Session after an exception occurs)'.
In other words, how do I get the Id-value of a new customer? Should I refresh the customer object manually or has NHibernate accommodations for this situation?
My mapping file looks like this:
Code:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0">
<class name="MyApp.Core.Domain.Customer, MyApp.Core" table="customer">
<id name="Id" type="Int32" column="customerid" unsaved-value="-1">
<generator class="identity"/>
</id>
<property name="Name" column="name" type="String" length="100"/>
</class>
</hibernate-mapping>