本文介绍了如何在 ServiceStack OrmLite 中检索自动递增的 ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 对于具有标识的表: [AutoIncrement] public int Id { get; set;}在数据库中插入新行时,检索对象Id的最佳方法是什么?When inserting a new row into the database, what is the best way to retrieve the Id of the object?例如:db.Insert (new User()); db.Insert<> (new User());插入后Id的值为0,但在数据库中显然不是这样.我能看到的唯一可能性如下:The value of the Id is 0 after the insert, but in the database this obviously is not the case. The only possibility I can see is the following:Id = (int)db.GetLastInsertId();但是,我认为这不是一个安全的电话.如果有 100 个插入同时发生,则可能返回另一个插入的 Id.在 EF 中,当您执行插入操作时,会为您设置 Id.However I don't believe this would be a safe call to make. If there are 100's of inserts happening at the same time, an Id for another insert may be returned. In EF when you do an insert the Id is set for you.有人知道解决这个问题的最佳方法吗?Does anyone know the best way to go about this?推荐答案在默认使用参数化查询的 ServiceStack.OrmLite v4 中,db.Save() 中有几个选项 自动填充 AutoIncrement Id,例如:In ServiceStack.OrmLite v4 which defaults to using parameterized queries there are a couple of options in db.Save() which automatically populates the AutoIncrement Id, e.g:db.Save(item);item.Id //populated with the auto-incremented id否则,您可以使用以下方法选择最后一个插入 ID:Otherwise you can select the last insert id using:var itemId = db.Insert(item, selectIdentity:true);这里是 更多展示 OrmLite 的示例新的 API .对于 OrmLite v3For OrmLite v3正确的调用是 db.GetLastInsertId(),例如对于 SQL Server,它在后台调用 SELECT SCOPE_IDENTITY() 返回该连接的最后插入的ID.The correct call is db.GetLastInsertId() which for SQL Server under the hood for example calls SELECT SCOPE_IDENTITY() which returns the last inserted id for that connection.这是安全的,因为可能发生的所有其他并发插入都使用不同的数据库连接.为了让其他人使用相同的连接,它需要被处理并释放回池中.This is safe because all the other concurrent inserts that might be happening are using different DB connections. In order for anyone else to use the same connection it needs to be disposed of and released back into the pool. 这篇关于如何在 ServiceStack OrmLite 中检索自动递增的 ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-20 19:48