插入数据时指定列,未被指定的列将被忽略。
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 | 设置连接对象 |
ToSql | string | 返回即将执行的SQL语句 | |
ExecuteAffrows | long | 执行SQL语句,返回影响的行数 | |
ExecuteIdentity | long | 执行SQL语句,返回自增值 | |
ExecuteInserted | List<T1> | 执行SQL语句,返回插入后的记录 | |
ExecuteSqlBulkCopy | void | SqlServer 特有的功能,执行 SqlBulkCopy 批量插入的封装 | |
ExecutePgCopy | void | PostgreSQL 特有的功能,执行 Copy 批量导入数据 |