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?