欢迎来到《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)
{
}

系列文章导航

相关文章:

  • 2022-12-23
  • 2021-08-23
  • 2021-04-20
  • 2022-01-19
  • 2021-08-30
  • 2022-12-23
  • 2021-10-28
猜你喜欢
  • 2021-07-08
  • 2021-09-30
  • 2021-08-24
  • 2022-12-23
  • 2022-12-23
  • 2022-03-07
  • 2021-07-10
相关资源
相似解决方案