1. 程式人生 > 實用技巧 >9.2 ABP基礎設施層 - 整合Dapper

9.2 ABP基礎設施層 - 整合Dapper

原文:https://github.com/ABPFrameWorkGroup/AbpDocument2Chinese/blob/master/Markdown/Abp/9.5ABP%E5%9F%BA%E7%A1%80%E8%AE%BE%E6%96%BD%E5%B1%82-%E9%9B%86%E6%88%90Dapper.md


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 作為傳入引數。這樣就可以註冊它到你的模組中了。

[DependsOn(
     typeof(AbpEntityFrameworkCoreModule),
     typeof(AbpDapperModule)
)]
public class MyModule
: AbpModule { public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(SampleApplicationModule).GetAssembly()); } }

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

9.2.4 實體與表的對映

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

public
class PersonMapper : ClassMapper<Person> { public PersonMapper() { Table("Persons"); Map(x => x.Roles).Ignore(); AutoMap(); } }

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

[DependsOn(
     typeof(AbpEntityFrameworkModule),
     typeof(AbpDapperModule)
)]
public class MyModule : AbpModule
{
    public override void Initialize()
    {
        IocManager.RegisterAssemblyByConvention(typeof(SampleApplicationModule).GetAssembly());

        //這裡會自動去掃描程式集中配置好的對映關係
        DapperExtensions.SetMappingAssemblies(new List<Assembly> { typeof(MyModule).GetAssembly() });
    }
}

9.2.5 使用

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

public class SomeApplicationService : ITransientDependency
{
    private readonly IDapperRepository<Person> _personDapperRepository;
    private readonly IRepository<Person> _personRepository;

    public SomeApplicationService(
        IRepository<Person> personRepository,
        IDapperRepository<Person> personDapperRepository)
    {
        _personRepository = personRepository;
        _personDapperRepository = personDapperRepository;
    }

    public void DoSomeStuff()
    {
        var people = _personDapperRepository.Query("select * from Persons");
    }
}

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