一個請求需要調用兩個不同的數據庫 添加DbContext


 

當請求進入application中的方法時 會開啟一個工作單元    這里面調用不同的DbContext 會默認使用第一次調用的DbContext  

需要手動開啟工作單元來隔離兩個不同的DbContext進行操作

 

ABP中出現這個問題 看看方法是不是異步的  返回類型是不是Task 

1.比如自己封裝了一個開啟工作單元的方法

        public async Task NewUnitOfWork(Func<Task> Func)
        {
            using (var unitOfWork = unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
            {
                try
                {
                    await Func.Invoke();
                    await unitOfWork.CompleteAsync();
                }
                catch (DbUpdateException)
                {

                    throw new UserFriendlyException("當前記錄已經被使用");
                }
                catch (Exception ex)
                {
                    throw new UserFriendlyException(ex.Message);
                }
            }
        }

2.這個委托里面會寫對數據庫的查詢操作  都是異步的  調用這個委托的時候 也是通過 await調用的 委托的返回值類型就要寫Task  不然就會報上面的錯誤

            await delUnitOfWork.NewUnitOfWork(async () =>
            {
                distributorGroupModel = await customerGroupGroupRepository.GetAll()
                    .Where(t => t.Name == "經銷商")
                    .Where(t => t.IsSystem == true)
                    .FirstOrDefaultAsync();
                if (distributorGroupModel == null)
                {
                    throw new UserFriendlyException("初始化數據不存在");
                }
                customer = await customerRepository.GetAsync(input.Id.Value);
            });

 

添加DbContext   配置連接字符串方式 

1.在Web項目的Startup入口配置Dbcontext連接字符串

這三種寫法一樣 都是獲取配置文件中的連接字符串

2.非Web項目 不存在Startup入口 可以在EF的Moduel中配置連接字符串  這個參數可以 直接寫連接字符串

如果這種方式報錯  就改成下面這樣

3.在MyDbContext中重寫OnConfiguring進行配置連接字符串

可以通過注入IConfigurationRoot對象來獲取appsetting.json配置文件        

        private readonly IConfigurationRoot _appConfiguration;

        public Startup(IHostingEnvironment env)
        {
            _appConfiguration = env.GetAppConfiguration();
        }

這個GetAppConfiguration是擴展方法  寫在 Web.Core層  所以Application層,Core層,EF層不能引用Web.Core層  所以不能調用這個擴展方法  通過這種方式調用  其實上面那個擴展方法里面就是調用了下面這個方法

        private readonly IConfigurationRoot _appConfiguration;

        public IMSEntityFrameworkModule(IHostingEnvironment env)
        {
            _appConfiguration = AppConfigurations.Get(env.ContentRootPath, env.EnvironmentName, env.IsDevelopment());
        }

 

 

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {

            // 從 appsetting.json 中獲取配置信息
            var config = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();

            optionsBuilder.UseSqlServer(config.GetConnectionString("DefaultConnection"));
        }

 

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            configuration = ConfigManager.LoadConfig("appsettings.json");
            optionsBuilder.UseSqlServer(configuration["ConnectionStrings"]);
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM