Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NHibernate "null identifier" exception after inserting an entity

Tags:

nhibernate

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?

like image 441
gilles27 Avatar asked Jun 11 '09 17:06

gilles27


2 Answers

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?

like image 85
Ben Avatar answered Sep 21 '22 10:09

Ben


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. :)

like image 36
Frederik Gheysels Avatar answered Sep 23 '22 10:09

Frederik Gheysels