0

我有一个如下映射的类:

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_InsertON,但我得到以下异常(在保留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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

谁能解释为什么我仍然得到那个例外?

4

1 回答 1

0

如果问题与Nathan Fisher建议的单独事务有关,那么 NHibernate 的ITransaction.Enlist(IDbCommand)方法应该可以解决它。尝试这样的事情:

using (var trx = session.BeginTransaction())
{
    ExecuteInNHTransaction(session, "SET IDENTITY_INSERT Foo ON");
    session.Save(myFoo);
    ExecuteInNHTransaction(session, "SET IDENTITY_INSERT Foo OFF");
    trx.Commit();
}
private static void ExecuteInNHTransaction(ISession session, string commandText)
{
    var command = new SqlCommand(commandText,
        (SqlConnection) session.Connection);
    session.Transaction.Enlist(command);
    command.ExecuteNonQuery();
}
于 2013-08-21T22:27:38.270 回答