I’m having trouble saving an entity into an SQL Server 2005 database. I’m using NHibernate 2.0.0.3002 for my persistence layer. The mapping is typical, with an integer ID, as follows
<id name="Id" unsaved-value="0">
<column name="Id"/>
<generator class="identity" />
</id>
I’ve omitted the rest for brevity. The application is using a repository class with a generic save method as follows
public void Save(T toSave)
{
Save(new T[] { toSave });
}
public void Save(IEnumerable<T> toSave)
{
using (ISession session = SessionFactory.OpenSession())
{
foreach (T item in toSave)
{
session.SaveOrUpdate(item);
}
session.Flush();
}
}
When calling SaveOrUpdate on the session, an exception is thrown with a message of “null identifier”. When I check the database the row has been inserted with all the correct values, so I think the problem is when NHibernate tries to set the Id property of the entity with the value returned by @@IDENTITY. I can see through SQL Profiler that @@IDENTITY is being called so I don’t understand why the exception is thrown.
Has anyone else had this problem?
Both Save and Delete must happen in a transaction and the transaction must be committed at the end.
like so:
please note: you’ll want to wrap that in a using and properly rollback… also, placement of where you’re opening and committing the transaction will matter based on your scenario. You should also close the transaction when you’re done…
Also, can you elaborate on where the exception is happening? It sounds like you’re saving a parent and then the child is throwing because the parent’s id is null? Or, is it actually throwing on saving the parent?