歡迎來到《FreeSql.Repository 倉儲模式》系列文檔,本系列文檔專注介紹 【倉儲+工作單元】 的使用方式。完整文檔請前往 wiki 中心:https://github.com/dotnetcore/FreeSql/wiki
FreeSql.Repository 作為 FreeSql.dll 的擴充,實作了通用倉儲層功能,開箱即可,可甜可鹹。
安裝
環境1、.NET Core 或 .NET 5.0+
dotnet add package FreeSql.Repository
環境2、.NET Framework
Install-Package FreeSql.DbContext
定義
使用 FreeSql.Repository 仍然需要提前建立 IFreeSql:
static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.Sqlite, connectionString)
.UseAutoSyncStructure(true) //自動遷移實體的結構到資料庫
.Build(); //請務必定義成 Singleton 單例模式
public class Song
{
[Column(IsIdentity = true)]
public int Id { get; set; }
public string Title { get; set; }
}
使用方法
方法1、IFreeSql 的擴充方法,在編碼中的任何地方都可以這樣使用;
var curd = fsql.GetRepository<Song>();
crud.Insert(new Song()); //插入
curd.Update(new Song { Id = 10, Title = "愛你一萬年" });
//...
注意:同一個 Repository 執行個體對象在多線程中使用不安全
repo.Insert 插入資料,适配各資料庫優化執行 ExecuteAffrows/ExecuteIdentity/ExecuteInserted
如果實體類有自增,插入後的值将回填給實體對象
方法2、繼承實作;
public class SongRepository : BaseRepository<Song, int>
{
public SongRepository(IFreeSql fsql) : base(fsql, null, null) {}
//在這裡增加 CURD 以外的方法
}
方法3、依賴注入;
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IFreeSql>(fsql);
services.AddFreeRepository(null, this.GetType().Assembly);
}
//在控制器使用
public SongController(IBaseRepository<Song> repo1, SongRepository repo2)
{
}
系列文章導航
- (一)什麼是倉儲
- (二)如何使用倉儲
- (三)實體特性
- (四)工作單元
- (五)狀态管理
- (六)導航屬性
- (七)多表查詢
- (八)級聯加載
- (九)級聯儲存
- (十)動态實體類型
- (十一)分表
- (十二)如何擴充