ABP入门教程(五)集成Dapper

如果在项目中要直接写T-SQL,可以引入Dapper

1,在EntityFrameworkCore层和Application层添加引用: Abp.Dapper

2,在EntityFrameworkModule类中添加两句代码就完成了配置

//1 在DependsOn中添加
typeof(AbpDapperModule)
//2 在 Initialize()方法中添加
DapperExtensions.DapperExtensions.SetMappingAssemblies(new List<Assembly> { typeof(ABP7VueEntityFrameworkModule).GetAssembly() });

最终效果如下

namespace ABP7Vue.EntityFrameworkCore
{
    [DependsOn(
        typeof(ABP7VueCoreModule), 
        typeof(AbpZeroCoreEntityFrameworkCoreModule),
        typeof(AbpDapperModule))]
    public class ABP7VueEntityFrameworkModule : AbpModule
    {
        /* Used it tests to skip dbcontext registration, in order to use in-memory database of EF Core */
        public bool SkipDbContextRegistration { get; set; }

        public bool SkipDbSeed { get; set; }

        public override void PreInitialize()
        {
            if (!SkipDbContextRegistration)
            {
                Configuration.Modules.AbpEfCore().AddDbContext<ABP7VueDbContext>(options =>
                {
                    if (options.ExistingConnection != null)
                    {
                        ABP7VueDbContextConfigurer.Configure(options.DbContextOptions, options.ExistingConnection);
                    }
                    else
                    {
                        ABP7VueDbContextConfigurer.Configure(options.DbContextOptions, options.ConnectionString);
                    }
                });
            }
        }

        public override void Initialize()
        {
            IocManager.RegisterAssemblyByConvention(typeof(ABP7VueEntityFrameworkModule).GetAssembly());
            DapperExtensions.DapperExtensions.SetMappingAssemblies(new List<Assembly> { typeof(ABP7VueEntityFrameworkModule).GetAssembly() });
        }

        public override void PostInitialize()
        {
            if (!SkipDbSeed)
            {
                SeedHelper.SeedHostDb(IocManager);
            }
        }
    }
}

3,在服务中注入Dapper的仓储就可以使用了

public class DepartmentAppService : ABP7VueAppServiceBase
{
    private readonly IDapperRepository<Department, int> _DapperRepository;

    public DepartmentAppService(IDapperRepository<Department, int> dapperRepository)
    {
        _DapperRepository = dapperRepository;
    }

    public List<Department> GetDepartmentList()
    {
        var a = new Department() { Code="Code0", Name="Name0", };
        _DapperRepository.Insert(a);
        _DapperRepository.Insert(new Department() { Code="Code1", Name="Name1", });
        _DapperRepository.Execute("INSERT INTO Department(Code, [Name], CreationTime, IsDeleted)VALUES      ('Code', 'Name', getdate(), 0)");
        var entity = _DapperRepository.Query("select * from Department").ToList();
        return entity;
    }
}

在ABP项目中实现自定义仓储举例

//在Core层添加仓储接口
public interface IXxxxxRepository
{
	Task<int> DoSomethingAboutDb(List<long> input, long userId);
}

//在EntityFrameworkCore层添加仓储实现, 继承Dapper仓储基类DapperEfRepositoryBase , 第一参数为DbContext, 第二参数为实体, 第三个参数为主键类型
public class XxxxxRepository : DapperEfRepositoryBase<EpiDbContext, Lab, long>, IXxxxxRepository, ITransientDependency
{
	ILogger Logger { get; set; }
	string _connectionStrings;

	public XxxxxRepository(IActiveTransactionProvider activeTransactionProvider, IHostingEnvironment env) : base(activeTransactionProvider)
	{
		var _appConfiguration = AppConfigurations.Get(env.ContentRootPath, env.EnvironmentName, env.IsDevelopment());
	    _connectionStrings = _appConfiguration["ConnectionStrings:Default"];
	}

	public async Task<int> DoSomethingAboutDb(List<long> input, long userId)
	{
		//创建临时表
		var sqlCreate = @"CREATE TABLE #expId(Id  BIGINT); ";

		//插入数据到临时表
		var sqlInsert = "";
		foreach (long expId in input)
		{
			sqlInsert +=  $" INSERT INTO #expId(Id) VALUES ({@expId}); ";
		}

		//执行存储过程
		var sqlSp = " exec spDoSomethingAboutDb @userId=@userId";

		string sql = sqlCreate + sqlInsert  + sqlSp;

		return await ExecuteAsync(sql, new { userId = userId });
	}
}

然后在应用层或core层直接注入此仓储就可以使用了

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值