I've been looking all over and can't find a good answer to this problem with NHibernate.
I'm working with an API that uses NHibernate. I'm doing a data transfer and I'm trying to use their User object to save user data.
I create the object
User objUser = new User();
They have a mapping file that specifies ids be set to identity
<id name="Id" column="UserId" type="int">
<generator class="native" />
</id>
but one of my requirements is to save the old id to the user table. I need to be able to temporarily set the identity insert to ON and save the record but still be able to use the User object to save the associated data.
I tried doing something like this
using (ISession session = MyDatabaseFactory.SessionFactory.OpenSession())
{
using (ITransaction trans = session.BeginTransaction())
{
session.CreateSQLQuery("SET IDENTITY_INSERT Users ON").UniqueResult();
session.Save(objUser, objUser.Id);
session.Flush();
trans.Commit();
session.CreateSQLQuery("SET IDENTITY_INSERT Users OFF").UniqueResult();
session.Close();
objUser= session1.Merge(objUser);
}
}
but when trying to save the user object again later like this
objUser.Passwords.Add("password1");
objUser.Save()
I get an error: a different object with the same identifier value was already associated with the session