我有一個問題,我試圖重新插入一個實體到我的數據庫。它說明與下面的單元測試:NHibernate的插入與identity_insert ON
// 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()」,但這似乎不是錯誤的根源。仍然得到同樣的結果
你想在表格中間的某處添加一個實體嗎?或者想在最後添加一個實體?我真的不明白你的邏輯,你爲什麼需要這樣做? – Rippo
如另一條評論所述,這是在雲應用程序中實現撤銷/重做邏輯,缺少自然鍵 – Shane
如果所有表都是標識列,並且您擁有數據庫完整性,那麼爲什麼密鑰必須返回原始位置州?我的評論也在你澄清之前......對不起,但我仍然不知道;得到你的邏輯 – Rippo