我有一个如下映射的类:
public class FooMap : ClassMap<Foo>
{
public FooMap()
{
Table("Foo");
LazyLoad();
CompositeId().KeyProperty(x => x.ID,
kp => kp.ColumnName("Id")
.Type(typeof(long)))
.KeyProperty(x => x.ValidFrom);
}
}
在 MSSQL 端,Id 是标识列,表的 PK 由Id
和组成ValidFrom
。
这是我用来保存的代码:
ISession session = SessionService.GetSession();
new SqlCommand("SET IDENTITY_INSERT Foo ON",
session.Connection as SqlConnection)
.ExecuteNonQuery();
try
{
// performs various versioning checks,
// then saves using transaction.
// The session is the same as above
GenericDataService.Save(myFoo);
}
finally
{
new SqlCommand("SET IDENTITY_INSERT Foo OFF",
session.Connection as SqlConnection)
.ExecuteNonQuery();
}
虽然我设置Identity_Insert
为ON
,但我得到以下异常(在保留ID
和设置 new时ValidFrom
):
Cannot insert explicit value for identity column in table 'Foo' when IDENTITY_INSERT is set to OFF.
这是执行的 SQL:
INSERT INTO Foo (C1, C2, C3, C4, C5, C6, C7, C8, C9, C10, Id, ValidFrom)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
谁能解释为什么我仍然得到那个例外?