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的仓储了。
posted on 2020-10-28 11:46 springsnow 阅读(951) 评论(0) 收藏 举报
浙公网安备 33010602011771号