插入数据时指定列,未被指定的列将被忽略。

var connectionString = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;" + 
    "Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10";static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
    .UseConnectionString(FreeSql.DataType.MySql, connectionString)
    .UseAutoSyncStructure(true) //自动同步实体结构到数据库
    .Build(); //请务必定义成 Singleton 单例模式class Topic {
    [Column(IsIdentity = true, IsPrimary = true)]    public int Id { get; set; }    public int Clicks { get; set; }    public string Title { get; set; }    public DateTime CreateTime { get; set; }
}var items = new List<Topic>();for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });

指定列

fsql.Insert<Topic>(items).InsertColumns(a => a.Title).ExecuteAffrows();

执行SQL如下:

INSERT INTO `tb_topic`(`Title`) 
VALUES(@Title0), (@Title1), (@Title2), (@Title3), (@Title4), 
(@Title5), (@Title6), (@Title7), (@Title8), (@Title9)
fsql.Insert<Topic>(items).InsertColumns(a =>new { a.Title, a.Clicks }).ExecuteAffrows();

执行SQL如下:

INSERT INTO `tb_topic`(`Clicks`, `Title`) 
VALUES(@Clicks0, @Title0), (@Clicks1, @Title1), (@Clicks2, @Title2), 
(@Clicks3, @Title3), (@Clicks4, @Title4), (@Clicks5, @Title5), (@Clicks6, @Title6), 
(@Clicks7, @Title7), (@Clicks8, @Title8), (@Clicks9, @Title9)

API

方法返回值参数描述
AppendData<this>T1 | IEnumerable追加准备插入的实体
InsertIdentity<this>指明插入自增列
InsertColumns<this>Lambda只插入的列
IgnoreColumns<this>Lambda忽略的列
CommandTimeout<this>int命令超时设置(秒)
WithTransaction<this>DbTransaction设置事务对象
WithConnection<this>DbConnection设置连接对象
ToSqlstring 返回即将执行的SQL语句
ExecuteAffrowslong 执行SQL语句,返回影响的行数
ExecuteIdentitylong 执行SQL语句,返回自增值
ExecuteInsertedList<T1> 执行SQL语句,返回插入后的记录
ExecuteSqlBulkCopyvoid SqlServer 特有的功能,执行 SqlBulkCopy 批量插入的封装
ExecutePgCopyvoid PostgreSQL 特有的功能,执行 Copy 批量导入数据