【发布时间】:2012-11-16 13:52:01
【问题描述】:
我在尝试将实体重新插入数据库时遇到问题。用下面的单元测试来说明:
// 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()”,但这似乎不是错误的根源。仍然得到相同的结果
【问题讨论】:
-
您是想在表格中间某处红色添加一个实体,还是想在最后添加一个实体?我真的不明白你的逻辑,你为什么需要这样做?
-
正如另一条评论中所说,这是在云应用程序中实现撤消/重做逻辑,缺少自然键
-
如果所有表都是标识列并且您具有数据库完整性,那么为什么密钥必须回到原始状态?我的评论也是在你澄清之前......对不起,但我还是不这样做;'明白你的逻辑
-
如果我更改了 ID,我必须将其传回给客户端,事情可能会变得非常混乱。只读客户端也无法执行工作
标签: nhibernate identity-insert