FreeSql 插入数据返回自增值

FreeSql是一个功能强大的 .NET ORM 功能库,支持 .NetFramework 4.0+、.NetCore 2.1+、Xamarin 等支持 NetStandard 所有运行平台。

以 MIT 开源协议托管于 github:https://github.com/2881099/FreeSql

FreeSql 插入数据的方式有多种,这篇文章教你用最优的方案做数据插入功能。

static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
    .UseConnectionString(FreeSql.DataType.Sqlite, "Data Source=db1.db")
    .UseAutoSyncStructure(true) //自动同步实体结构到数据库 .Build(); //请务必定义成 Singleton 单例模式 public class Blog { [Column(IsIdentity = true, IsPrimary = true)] public int BlogId { get; set; } public string Url { get; set; } public int Rating { get; set; } } var blog = new Blog { Url = "https://github.com/2881099/FreeSql", Rating = 5 }; 

单条数据插入

如果表有自增列,插入数据后应该要返回 id。

方法1:(原始)

long id = fsql.Insert(blog).ExecuteIdentity();
blog.Id = id;

方法2:(依赖 FreeSql.Repository)

var repo = fsql.GetRepository<Blog>();
repo.Insert(blog);

将插入后的自增值,填充给 blog.Id

方法3:(依赖 FreeSql.DbContext)

using (var ctx = fsql.CreateDbContext())
{
	ctx.Add(blog);
	ctx.SaveChanges();
}

将插入后的自增值,填充给 blog.Id

批量插入

var items = new List<Topic>();
for (var a = 0; a < 10; a++) { items.Add(new Blog { Url = "https://github.com/2881099/FreeSql", Rating = 5 }); } 

方法1:(原始)

fsql.Insert(items).ExecuteAffrows();

无法返回 items 所有 id 值

方法2:(依赖 FreeSql.Repository)

var repo = fsql.GetRepository<Blog>();
repo.Insert(items);

将插入后的自增值,填充给所有 items.Id

当操作的是 SqlServer/PostgreSql 数据库,此方法为一次执行,返回所有 id

当操作的是其他数据库,此方法为循环多次执行,返回所有 id(注意性能问题)

大批量插入(SqlBulkCopy、BulkCopy)

针对 SqlServer/PostgreSQL/MySql 数据库,目前能在以下实现使用:

  • FreeSql.Provider.SqlServer
  • FreeSql.Provider.PostgreSQL
  • FreeSql.Provider.MySqlConnector
fsql.Insert(items).ExecuteSqlBulkCopy();
fsql.Insert(items).ExecutePgCopy();
fsql.Insert(items).ExecuteMySqlBulkCopy();

另外 IInsert 方法提供了 ToDataTable() 方法返回 DataTable 对象,让使用者自己封装 BulkCopy 操作。

DataTable dt = fsql.Insert(items)
	.InsertIdentity() //开启自增 id 插入
	.ToDataTable();

注意:InsertIdentity() 的功能是生成 SQL 的时候有值,而不是调用 SET IDENTITY ON;

来源:http://www.1994july.club/

猜你喜欢

转载自www.cnblogs.com/1994july/p/12442365.html