想要在事务中的后续插入中使用从插入返回的身份
我使用 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
}),
};
I'm using Rob Conery's Massive for database access. I want to wrap a transaction around a couple of inserts but the second insert uses the identity returned from the first insert. It's not obvious to me how to do this in a transaction. Some assistance would be appreciated.
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
}),
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在这两个插入之间进行查询,Massive 中的此方法可能很有用:
您的 sql 将 = "selectscope_identity()"
UPDATE 2013/02/26
再次查看 Massive 代码,没有可靠的方法检索最后插入的 ID 的方法。
上面的代码仅在创建“selectscope_identity()”的连接被池化时才有效。 (必须与插入的连接相同)。
Massive
table.Insert(..)
方法返回包含 ID 字段的 Dynamic,该字段填充为“SELECT @@IDENTITY”。它从全局范围获取最后插入的 ID,这是一个明显的错误(在多线程场景中很明显)。Make a query between those two inserts, this method from Massive may be useful:
Your sql will be = "select scope_identity()"
UPDATE 2013/02/26
Looking again at the Massive code there is no reliable way to retrieve last inserted ID.
Code above will work only when connection that makes "select scope_identity()" is pooled. (It must be the same connection that made insert).
Massive
table.Insert(..)
method returns Dynamic that contains ID field, which is filled with "SELECT @@IDENTITY". It gets last inserted ID from global scope, which is obvious bug (apparent in multithreading scenarios).你可以在存储过程中完成它吗?您可以使用scope_identity或更好的输出子句来获取您需要的值。对所有表的所有插入都在一个事务中,如果其中任何一个失败,则可以回滚。
Can you just do it in a stored proc? The you can use scope_identity or better yet the output clause to get the value(s) you need. And all the inserts to all the tables are in one transaction which can be rolled back if any of them fail.