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;
參考資料
| 《新人學習指引》 | 《Select》 | 《Update》 | 《Insert》 | 《Delete》 | |
| 《表達式函數》 | 《CodeFirst》 | 《DbFirst》 | 《BaseEntity》 | |
| 《Repository》 | 《UnitOfWork》 | 《過濾器》 | 《樂觀鎖》 | 《DbContext》 | |
| 《讀寫分離》 | 《分區分表》 | 《租戶》 | 《AOP》 | 《黑科技》 | 更新日志 |
