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:
public void Save(IEnumerable<T> toSave)
{
using (ISession session = SessionFactory.OpenSession())
{
ITransaction transaction = Session.BeginTransaction();
foreach (T item in toSave)
{
session.SaveOrUpdate(item);
}
transaction.Commit();
session.Flush();
}
}
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?
It is maybe helpfull to configure log4net so that you can log and view the actions that NHibernate is doing ...
I once had a problem with NHibernate using Access as well, and was able to solve it by setting up logging so that I could exactly pinpoint the cause of the problem.
The error-message that I received, was different from yours, but this is the article in where I describe how I solved my problem. Perhaps it could be helpfull for you to. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With