歡迎來到《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)
{
}