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 作为传入参数。这样就可以注册它到你的模块中了。

[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的仓储了。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值