NHibernate null identifier exception after inserting an object

I'm having trouble saving an object in a SQL Server 2005 database. I am using NHibernate 2.0.0.3002 for my save level. The mapping is typically with an integer identifier, as follows

<id name="Id" unsaved-value="0">
  <column name="Id"/>
  <generator class="identity" />
</id>

I left the rest for brevity. The application uses the repository class with a common save method, as shown below.

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();
    }
}

SaveOrUpdate " ". , ​​ , , , NHibernate Id , @@IDENTITY. SQL Profiler, @@IDENTITY , , .

- ?

+5
5

, .

:

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();
    }
}

: ... , , , . , ...

, , ? , , , ? ?

+8

, log4net, , NHibernate...

- NHibernate Access, , , .

, , , this - , , , , .:)

+1

NHibernate. , , , , , . Int HiLo .

, , ...

<id name="Id" column="Id" unsaved-value="0">
   <generator class="identity"/>  
</id>
0

I also had this error, and the solution was to wrap it in a transaction, as Ben mentioned. However, I could not get the Ben and gilles27 code, perhaps because I am new to generics and NHibernate. I created a slightly different implementation that works (using Fluent NHibernate v1.3):

        public static ISession LocalDbSession = null;

    public static void Save<T>(T toSave)
    {
        using (var transaction = LocalDbSession.BeginTransaction())
        {
            LocalDbSession.Save(toSave);
            transaction.Commit();
            LocalDbSession.Flush();
        }
    }

    public static void Save<T>(IEnumerable<T> toSave)
    {
        using (var transaction = LocalDbSession.BeginTransaction())
        {
            foreach (T item in toSave)
            {
                LocalDbSession.Save(item);
            }

            transaction.Commit();
            LocalDbSession.Flush();
        }
    }
0
source

I think instead of the generator class = "identitiy" / ">

try class = "guid.comp" generator

-2
source

All Articles