之前,一直想集成Dapper到項目中,但是一直沒成功,今天把abp升級到最新版,然后按教程來,就可以了,呵呵
現在,基於上一篇的源碼進行升級和集成dapper,將abp升級到3.8.2
官方升級文檔: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
一、注冊Module
首先,你要在Module類上添加 DependsOn 特性,並且使用 AbpDapperModule 作為傳入參數。依賴關系的先后順序 AbpDapperModule 依賴應該在 EF Core依賴之后。
修改ZmBlog.Infrastructure的ZmBlogDataModule 如下:
namespace ZmBlog.EntityFramework { [DependsOn(typeof(ZmBlogCoreModule), typeof(AbpEntityFrameworkModule), typeof(AbpDapperModule))] public class ZmBlogDataModule : AbpModule { public override void PreInitialize() { Database.SetInitializer(new CreateDatabaseIfNotExists<ZmBlogDbContext>()); Configuration.DefaultNameOrConnectionString = "DefaultConnection"; } public override void Initialize() { IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly()); DapperExtensions.DapperExtensions.SetMappingAssemblies(new List<Assembly> { typeof(ZmBlogDataModule).GetAssembly() }); } } }
二、配置實體與表的映射
和ef一樣,需要配置映射關系
public class PersonMapper : ClassMapper<Category> { public PersonMapper() { Table("Categories"); AutoMap(); } }
PS: 如果同時使用ef,它的映射最好使用ToTable指定表名,不然ef會自動轉換最后一個單詞為復數
三、使用
1.在應用層使用
private readonly IRepository<Category, string> _categoryRepository; private readonly IDapperRepository<Category, string> _categoryDapperRepository; private readonly ICategoryDapperRepository _categoryDapperRepo; public CategoryApp(IRepository<Category, string> categoryRepository, IDapperRepository<Category, string> categoryDapperRepository, ICategoryDapperRepository categoryDapperRepository2) { _categoryRepository = categoryRepository; _categoryDapperRepository = categoryDapperRepository; _categoryDapperRepo = categoryDapperRepository2; }
2.DapperRepository的封裝
封裝的倉儲基類
namespace ZmBlog.EntityFramework.EntityFramework.DapperRepositories { public abstract class DapperRepository<TEntity, TPrimaryKey> : DapperEfRepositoryBase<ZmBlogDbContext, TEntity, TPrimaryKey> where TEntity : class, IEntity<TPrimaryKey> { public DapperRepository(IActiveTransactionProvider activeTransactionProvider) : base(activeTransactionProvider) { } } public abstract class DapperRepository<TEntity> : DapperEfRepositoryBase<ZmBlogDbContext, TEntity, string> where TEntity : class, IEntity<string> { public DapperRepository(IActiveTransactionProvider activeTransactionProvider) : base(activeTransactionProvider) { } } }
定義倉儲接口和實現
//領域層 public interface ICategoryDapperRepository : IDapperRepository<Category, string> { } //基礎設施層 public class CategoryDapperRepository : DapperRepository<Category, string>, ICategoryDapperRepository { public CategoryDapperRepository(IActiveTransactionProvider activeTransactionProvider) : base(activeTransactionProvider) { } }
