5

我正在使用 Rob Conery 的Massive进行数据库访问。我想围绕几个插入包装一个事务,但第二个插入使用从第一个插入返回的标识。在交易中如何做到这一点对我来说并不明显。一些帮助将不胜感激。

var commandList = new List<DbCommand>
    {
        contactTbl.CreateInsertCommand(new
            {
                newContact.Name,
                newContact.Contact,
                newContact.Phone,
                newContact.ForceChargeThreshold,
                newContact.MeterReadingMethodId,
                LastModifiedBy = userId,
                LastModifiedDate = modifiedDate,
            }),
        branchContactTbl.CreateInsertCommand(new
            {
                newContact.BranchId,
                ContactId = ????, <-- how to set Id as identity from previous command
            }),
    };
4

2 回答 2

2

在这两个插入之间进行查询,Massive 的这种方法可能很有用:

public object Scalar(string sql, params object[] args) {
    object result = null;
    using (var conn = OpenConnection()) {
        result = CreateCommand(sql, conn, args).ExecuteScalar();
    }
    return result;
} 

你的 sql 将是 = "select scope_identity()"

更新 2013/02/26

再次查看大规模代码,没有可靠的方法来检索最后插入的 ID。

上面的代码仅在使“select scope_identity()”的连接被池化时才有效。(它必须与插入的连接相同)。

Massivetable.Insert(..)方法返回包含 ID 字段的 Dynamic,该字段用“SELECT @@IDENTITY”填充。它从全局范围获取最后插入的 ID,这是明显的错误(在多线程场景中很明显)。

于 2011-03-23T21:51:18.250 回答
1

你可以在存储过程中做到这一点吗?您可以使用 scope_identity 或更好的输出子句来获取您需要的值。并且所有表的所有插入都在一个事务中,如果其中任何一个失败,可以回滚。

于 2013-02-26T19:44:14.180 回答