我有一个问题,我试图将实体重新插入到我的数据库中。用以下单元测试说明:
// entity mapped to dbo.IdentityInsertTest table
// dbo.IdentityInsertTest has an IDENTITY Primary Key, Id
var id = (long)NHibernateSession1.Save(new IdentityInsertTest());
NHibernateSession1.Flush();
// delete previously created row
ExecuteNonQuery("DELETE FROM dbo.IdentityInsertTest");
try
{
// set entity insert off so that I can re-insert
NHibernateSession2.CreateSQLQuery("SET IDENTITY_INSERT dbo.IdentityInsertTest ON").UniqueResult();
// re-create deleted row with explicit Id
NHibernateSession2.Save(new IdentityInsertTest { Id = id });
NHibernateSession2.Flush();
Assert.AreEqual(1, ExecuteScalar("SELECT COUNT(1) FROM dbo.IdentityInsertTest"));
// this assert fails: expected 1, actual 2
Assert.AreEqual(id, ExecuteScalar("SELECT TOP 1 [Id] FROM dbo.IdentityInsertTest"));
}
finally
{
NHibernateSession2.CreateSQLQuery("SET IDENTITY_INSERT dbo.IdentityInsertTest OFF").UniqueResult();
}
我的映射很简单:
<class name="IdentityInsertTest" table="IdentityInsertTest">
<id name="Id" type="long">
<generator class="native" />
</id>
<property name="Data" type="int" not-null="false" />
</class>
据我所知,问题是 NHibernate 生成器仍然以某种方式从 SQL 调用身份生成,即使我已将其关闭。有没有办法解决?
编辑:我最初在设置 IDENTITY_INSERT 时忘记执行“UniqueResult()”,但这似乎不是错误的根源。仍然得到相同的结果