Skip to content
shuxin edited this page Dec 10, 2023 · 2 revisions

插入数据

Chloe 具备多种插入数据的方式。

1.实体插入:

该方式插入,如果一个实体存在自增列,会自动将自增列设置到相应的属性上。

Person person = new Person();
person.Name = "Chloe";
person.Age = 18;
person.Gender = Gender.Male;
person.CityId = 1;
person.CreateTime = DateTime.Now;

/* 会自动将自增 Id 设置到 person 的 Id 属性上 */
person = dbContext.Insert(person);
/*
 * String @P_0 = 'Chloe';
   Int32 @P_1 = 1;
   Int32 @P_2 = 18;
   DateTime @P_3 = '2018/8/8 16:06:58';
   DateTime @P_4 = NULL;
   INSERT INTO [Person]([Name],[Gender],[Age],[CityId],[CreateTime],[EditTime]) 
   VALUES(@P_0,@P_1,@P_2,@P_1,@P_3,@P_4);SELECT @@IDENTITY
 */

null 或空字符串不参与插入:

以上插入会将所有映射属性都插入到数据库,Chloe.ORM 支持设置属性值为 null 或空时对应的属性不参与插入。

DbContext dbContext = new MsSqlContext("Data Source = .;Initial Catalog = Chloe;Integrated Security = SSPI;");
//dbContext.Options.InsertStrategy = InsertStrategy.IgnoreNull;  //插入时忽略值为 null 的属性
//dbContext.Options.InsertStrategy = InsertStrategy.IgnoreEmptyString;  //插入时忽略字符串值为 "" 的属性
dbContext.Options.InsertStrategy = InsertStrategy.IgnoreNull | InsertStrategy.IgnoreEmptyString;  //插入时忽略值为 null 和字符串值为空字符串的属性

Person person = new Person();
person.Name = "";
person.Age = 18;
person.Gender = Gender.Female;
person.CityId = 1;
person.CreateTime = DateTime.Now;
person.EditTime = null;

//设置属性值为 null 和字符串空值不参与插入
(this.DbContext as DbContext).Options.InsertStrategy = InsertStrategy.IgnoreNull | InsertStrategy.IgnoreEmptyString;

//插入时 Name 和 EditTime 属性不会生成到 sql 语句中
person = this.DbContext.Insert(person);
/*
 * Input Int32 @P_0 = 2;
   Input Int32 @P_1 = 18;
   Input Int32 @P_2 = 1;
   Input DateTime @P_3 = '2023/12/7 1:09:08';
   Input Int32 @P_4 = 0;
   INSERT INTO [Person]([Gender],[Age],[CityId],[CreateTime],[RowVersion]) VALUES(@P_0,@P_1,@P_2,@P_3,@P_4);SELECT LAST_INSERT_ROWID()
 */

2.lambda 方式插入:

此种方式插入的好处是,可以指定列插入,就像写 sql 一样简单。

同时,该方式插入返回表主键值。如果实体主键是自增列,返回值就会是自增值。

/* 返回主键 Id。tip:必须在 lambda 里写 new Person() */
int id = (int)this.DbContext.Insert<Person>(() => new Person()
{
    Name = "Chloe",
    Age = 18,
    Gender = Gender.Male,
    CityId = 1,
    CreateTime = DateTime.Now
});
/*
 * INSERT INTO [Person]([Name],[Age],[Gender],[CityId],[CreateTime]) 
   VALUES(N'Chloe',18,1,1,GETDATE());SELECT @@IDENTITY
 */

BulkInsert:

Chloe.SqlServer.BulkInsert() 方法可以将大批量的数据插入 SqlServer,内部实现基于 SqlBulkCopy。方法定义位于https://github.com/shuxinqin/Chloe/blob/master/src/Chloe.SqlServer/MsSqlContext.cs

使用方式如下:

List<TestEntity> entities = new List<TestEntity>();
for (int i = 0; i < 100000; i++)
{
    entities.Add(new TestEntity()
    {
        F_Byte = 1,
        F_Int16 = 1,
        F_Int32 = i,
        F_Int64 = i,
        F_Double = i,
        F_Float = i,
        F_Decimal = i,
        F_Bool = true,
        F_DateTime = DateTime.Now,
        F_String = "lu" + i.ToString()
    });
}

dbContext.BulkInsert(entities);