mirror of https://github.com/abpframework/abp
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
2.0 KiB
2.0 KiB
Dapper 集成
Dapper 是轻量化的数据库提供者,使用Dapper主要的好处是编写T-SQL查询,它为 IDbConnection 接口提供了一些扩展方法.
ABP没有为Dapper封装许多功能, ABP Dapper库在ABP EntityFrameworkCore的基础上提供了 DapperRepository<TDbContext> 基类,在其中提供了Dapper需要的IDbConnection和IDbTransaction属性,这两个属性可以和工作单元很好的配合.
安装
请先根据EF Core的集成文档安装并配置好EF Core.
Volo.Abp.Dapper是Dapper集成的主要nuget包.
将其安装到你的项目中(在分层应用程序中适用于 数据访问/基础设施层):
Install-Package Volo.Abp.Dapper
然后添加 AbpDapperModule 模块依赖项(DependsOn Attribute) 到 module(项目中的Mudole类):
using Volo.Abp.Dapper;
using Volo.Abp.Modularity;
namespace MyCompany.MyProject
{
[DependsOn(typeof(AbpDapperModule))]
public class MyModule : AbpModule
{
//...
}
}
实现Dapper仓储
下面的代码实现了Person仓储, 它需要EF Core的DbContext(MyAppDbContext). 你可以注入PersonDapperRepository来调用它的方法.
DbConnection和DbTransaction来自于DapperRepository基类.
public class PersonDapperRepository : DapperRepository<MyAppDbContext>, ITransientDependency
{
public PersonDapperRepository(IDbContextProvider<MyAppDbContext> dbContextProvider)
: base(dbContextProvider)
{
}
public virtual async Task<List<string>> GetAllPersonNames()
{
return (await DbConnection.QueryAsync<string>("select Name from People", transaction: DbTransaction))
.ToList();
}
public virtual async Task<int> UpdatePersonNames(string name)
{
return await DbConnection.ExecuteAsync("update People set Name = @NewName", new { NewName = name },
DbTransaction);
}
}