Dapper Integration

Dapper is a light-weight and simple database provider. The major benefit of using Dapper is writing T-SQL queries. It provides some extension methods for IDbConnection interface.

ABP does not encapsulate many functions for Dapper. ABP Dapper library provides a DapperRepository<TDbContext> base class based on ABP EntityFrameworkCore module, which provides the IDbConnection and IDbTransaction properties required by Dapper.

IDbConnection and IDbTransaction works well with the ABP Unit-Of-Work.

Installation

Install and configure EF Core according to EF Core’s integrated documentation.

Volo.Abp.Dapper is the main nuget package for the Dapper integration.

You can find it on NuGet Gallery: https://www.nuget.org/packages/Volo.Abp.Dapper

Install it to your project (for a layered application, to your data/infrastructure layer):

  1. Install-Package Volo.Abp.Dapper

Then add AbpDapperModule module dependency (with DependsOn attribute) to your module:

  1. using Volo.Abp.Dapper;
  2. using Volo.Abp.Modularity;
  3. namespace MyCompany.MyProject
  4. {
  5. [DependsOn(typeof(AbpDapperModule))]
  6. public class MyModule : AbpModule
  7. {
  8. //...
  9. }
  10. }

Implement Dapper Repository

The following code creates the PersonRepository, which requires EF Core’s DbContext (MyAppDbContext). You can inject PersonDapperRepository to your services for your database operations.

DbConnection and DbTransaction comes from the DapperRepository base class.

  1. public class PersonDapperRepository : DapperRepository<MyAppDbContext>, ITransientDependency
  2. {
  3. public PersonDapperRepository(IDbContextProvider<MyAppDbContext> dbContextProvider)
  4. : base(dbContextProvider)
  5. {
  6. }
  7. public virtual async Task<List<string>> GetAllPersonNames()
  8. {
  9. return (await DbConnection.QueryAsync<string>("select Name from People", transaction: DbTransaction))
  10. .ToList();
  11. }
  12. public virtual async Task<int> UpdatePersonNames(string name)
  13. {
  14. return await DbConnection.ExecuteAsync("update People set Name = @NewName", new { NewName = name },
  15. DbTransaction);
  16. }
  17. }