Skip to content

插入

插入相关 builder 都有同步和异步两套 API。下面先给出最常用的写法;如果你的调用链已经是 async,把 Execute 换成 ExecuteAsync 即可。

如果实体上的某个字段标记了 DatabaseGenerated,插入时会自动跳过它。

插入单条记录

csharp
int affectedRows = Db.Insert(entity).Execute();
csharp
int affectedRows = await Db.Insert(entity).ExecuteAsync();

插入多条记录

csharp
int affectedRows = Db.InsertMany(entities).Execute();

插入并获取数据库生成的 ID

csharp
int id = Db.InsertAndGetId(entity).Execute<int>();
csharp
int id = await Db.InsertAndGetId(entity).ExecuteAsync<int>();

插入或忽略(单条)

csharp
int affectedRows = Db.InsertOrIgnore(entity).Execute();

插入或忽略(多条)

csharp
int affectedRows = Db.InsertOrIgnoreMany(entities).Execute();

插入或替换(单条)

csharp
int affectedRows = Db.InsertOrReplace(entity).Execute();

插入或替换(多条)

csharp
int affectedRows = Db.InsertOrReplaceMany(entities).Execute();

插入指定列

csharp
int affectedRows = Db.Insert<EntityClass>()
    .Set(i => i.Id, entity.Id)
    .Set(i => i.Name, entity.Name)
    .Execute();

插入到指定表(单条)

csharp
int affectedRows = Db.Insert(entity)
    .To(table)
    .Execute();

其余插入类方法也都提供对应的 Async 版本,命名规则保持一致。