当使用 OrmLite 向数据库中添加条目时,似乎有两种方法:
dbConn.Insert(customer);
和
dbConn.Save(customer);
使用 Insert() 时,AutoIncrement ID 字段不会更新,但使用 Save() 时会更新。
如果您使用:
dbConn.LastInsertId();
如果使用 Save() 它将返回正确的 ID,但如果使用 Insert() 则返回错误的 ID。
为什么会有这两种方法?使用 Insert() 将使用正确的 ID 添加一个条目到数据库,它只是没有反射(reflect)在 POCO 模型中。没有抛出异常也没有指示问题似乎很奇怪,如果您没有意识到这一点,您最终可能会使用错误的 ID 并且很难跟踪错误。
最佳答案
文档中已经提到了:
Save and SaveAll will Insert if no record with Id exists, otherwise it Updates. Both take multiple items, optimized to perform a single read to check for existing records and are executed within a sinlge transaction.
对于Insert操作来说,很简单,没有什么特别的功能。
因此,当您知道记录中没有重复键时使用 Insert,否则使用 save 方法。
如果你想通过 Insert 方法获取 LastInsertId,你需要在你的 POCO 上指定 [AutoIncrement]。
UPDATE: When you set your IDbConnectionFactory using Singelton With Lazy< T > implementation, it seems the LastInsertId will not working. so just use lock or static implementation.
关于c# - OrmLite 更新()与保存(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20941820/