1. 程式人生 > 實用技巧 >ABP整合Dapper

ABP整合Dapper

9.2 ABP基礎設施層 - 整合Dapper

9.2.1 簡介

Dapper 是基於.NET的一種物件關係對映工具。Abp.Dapper簡單的將Dapper整合到ABP。它作為第二個ORM可以與EF 6.x, EF Core 或者 Nhibernate 工作。

9.2.2 安裝

在開始之前,你需要安裝Abp.Dapper以及 EF 6.x, EF Core 或者 NHibernate 這3個當中的任意一個你想用的到專案中。

9.2.3 註冊Module

首先你要在Module類上新增 DependsOn 特性,並且使用 AbpDapperModule 作為傳入引數。這樣就可以註冊它到你的模組中了。

  1. [DependsOn(
  2. typeof(AbpEntityFrameworkCoreModule),
  3. typeof(AbpDapperModule)
  4. )]
  5. public class MyModule : AbpModule
  6. {
  7. public override void Initialize()
  8. {
  9. IocManager.RegisterAssemblyByConvention(typeof(SampleApplicationModule).GetAssembly());
  10. }
  11. }

注意:依賴關係的先後順序 AbpDapperModule 依賴應該在 EF Core依賴之後。

9.2.4 實體與表的對映

你可以配置對映。例如:實體 Person 與表 Persons 的對映,如下所示:

  1. public class PersonMapper : ClassMapper<Person>
  2. {
  3. public PersonMapper()
  4. {
  5. Table("Persons");
  6. Map(x => x.Roles).Ignore();
  7. AutoMap();
  8. }
  9. }

你應該在模組類中配置包含Mapper類。例如:

  1. [DependsOn(
  2. typeof(AbpEntityFrameworkModule),
  3. typeof(AbpDapperModule)
  4. )]
  5. public class MyModule : AbpModule
  6. {
  7. public override void Initialize()
  8. {
  9. IocManager.RegisterAssemblyByConvention(typeof(SampleApplicationModule).GetAssembly());
  10. //這裡會自動去掃描程式集中配置好的對映關係
  11. DapperExtensions.SetMappingAssemblies(new List<Assembly> { typeof(MyModule).GetAssembly() });
  12. }
  13. }

9.2.5 使用

在註冊完 AbpDapperModule 後,你可以使用泛型 IDapperRepository 介面(而不是使用標準的IRepository)來注入dapper倉儲。

  1. public class SomeApplicationService : ITransientDependency
  2. {
  3. private readonly IDapperRepository<Person> _personDapperRepository;
  4. private readonly IRepository<Person> _personRepository;
  5. public SomeApplicationService(
  6. IRepository<Person> personRepository,
  7. IDapperRepository<Person> personDapperRepository)
  8. {
  9. _personRepository = personRepository;
  10. _personDapperRepository = personDapperRepository;
  11. }
  12. public void DoSomeStuff()
  13. {
  14. var people = _personDapperRepository.Query("select * from Persons");
  15. }
  16. }

這樣你就可以在相同的事務下,同時使用基於EF的倉儲和Dapper的倉儲了。