c# - OrmLite 更新()与保存()

标签 c# sql-server-2012 ormlite-servicestack

当使用 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/

相关文章:

azure - SSMS 对象资源管理器上未显示数据库

ServiceStack.Ormlite 单个 poco 映射到多个表

c# - 如何从 3.5 asmx web 服务获取 JSON 响应

c# - 如何防止在 mvc 中多次选择 Razor 控件单选按钮?

c# - 自引用实体 - 多对多

sql-server - 如何重命名sql server 2012实例名称独立服务器配置

c# - C# 中多次转换的规则是什么?

sql - 如何从 SQL Server 2012 中表的一个分区获取 COUNT(*)?

servicestack - Service.OrmLite 中的谓词错误地返回枚举值

sqlite - ServiceStack SqLite创建计算字段