📚
Hoa Framework
  • 一、框架指南
  • 二、功能特性
  • 三、源码结构
  • 四、代码规范
  • 五、入门指南
  • 六、依赖注入/控制反转
  • 七、控制器和服务
  • 八、对象映射指南
  • 九、数据库操作指南
    • 9.1、正向工程(Code First)
    • 9.2、逆向工程(Database First)
    • 9.3、关于仓储(IRepository)
    • 9.4、增删改操作
    • 9.5、查询操作
    • 9.6、DataSet、DataTable 操作
    • 9.7、查询结果集映射
    • 9.8、批量增删改操作
    • 9.9、存储过程、视图、函数操作
    • 9.10、工作单元和事务
    • 9.11、多上下文、读写分离
    • 9.12、切面上下文(TangentDbContext)
    • 9.13、其他操作
    • 9.14、EF Core 高性能
    • 9.15、常见错误
  • 十、开放接口指南
    • 10.1、RESTFul 和 Swagger
    • 10.2、规范化返回值
  • 十一、数据校验
  • 十二、安全授权
  • 十三、异常处理
  • 十四、日志管理
  • 十五、配置管理
  • 十六、缓存管理
  • 十七、内置工具类
    • 17.1、数据加解密
  • 十八、跨域处理
  • 十九、筛选拦截器(未)
  • 二十、进程服务(Daemon)
  • 二十一、编写测试
    • 20.1、单元测试
    • 20.2、基准测试
    • 20.3、性能测试
  • 二十二、托管部署
    • 22.1、IIS 托管部署
    • 22.2、Nginx 托管部署
    • 22.3、Docker 容器部署
  • 二十三、性能分析(MiniProfiler)
  • 二十四、其他功能
    • 23.1、第三方包管理
    • 23.2、文件上传下载
    • 23.3、Razor 视图引擎
    • 23.4、生成客户端请求代码
    • 23.5、快捷操作
  • 二十五、Docker 容器化
    • 25.1、Docker 介绍
    • 25.2、Docker 安装
    • 25.3、Docker 安装服务
    • 25.4、Docker 常用命令
    • 25.6、Docker run 常用命令
    • 25.7、Docker-Compose 介绍
    • 25.8、docker-compose.yml
    • 25.9、Docker-Compose 常用命令
    • 25.10、Docker-Compose 转换 docker run
    • 25.11、Docker 构建自己的镜像
    • 25.12、Dockerfile指南
    • 25.13、Dockerfile 常用命令
    • 25.14、Dockerfile 打包、上传、分享
    • 25.15、Docker 数据卷
    • 25.16、Docker 域网络
    • 25.17、Docker + Nginx 实现分布式集群、负载均衡
  • 二十六、DevOps 持续部署集成
    • 26.1、DevOps 介绍
    • 26.2、持续集成、交付、部署
    • 26.3、Jenkins 介绍
    • 26.4、Jenkins 安装
    • 26.5、Jenkins 初始化
    • 26.6、Jenkins 实战演练
    • 26.7、Jenkis 项目配置
    • 26.8、Jenkins 插件
  • 二十七、OpenXml/Excel 操作
  • 二十八、SaaS 多租户
  • 二十九、Git 代码管理
    • 29.1、Git 介绍
    • 29.2、Git 安装
    • 29.3、Git 基础配置
    • 29.4、Git 工作流程
    • 29.5、Git 重要概念
    • 29.6、Git 创建仓库
    • 29.7、Git 基本操作
    • 29.8、Git 分支管理
    • 29.9、Git 查看提交历史
    • 29.10、Git 标签
    • 29.11、Git 拉取/获取/推送
    • 28.12、Git GUI工具
    • 29.13、Git 私有化部署
    • 29.14、Git 推荐开发模式
    • 29.15、Svn 转 Git
  • 贡献代码
  • 更新日志
由 GitBook 提供支持
在本页
  • 多上下文
  • 多上下文配置使用
  • 第一步
  • 第二步
  • 第三步
  • 第四步
  • 第五步
  • 第六步
  • 读写分离配置
  • 关于分布式事务

这有帮助吗?

  1. 九、数据库操作指南

9.11、多上下文、读写分离

一个复杂的系统通常不止一个数据库,这是需要我们能够灵活的切换数据库操作上下文。

多上下文

默认情况下,Hoa Framework 只有一个默认的数据库上下文:Hoa.EntityFramewok.Core.HoaDbContext,也就是默认只能操作一个数据库。

在 Hoa Framework 1.2.0 版本中,新增了多数据库上下文的支持。通过配置数据库多上下文可以同时操作多个数据库、并将数据库包裹在同一个事务中。

多上下文配置使用

第一步

在 appsetting.json 中新增新的数据库连接字符串。

{
  "ConnectionStrings": {
    "HoaDatabase": "Server=localhost;Database=Hoa;User=sa;Password=000000;",
    "OtherDatabase": "Server=localhost;Database=Hoa;User=sa;Password=000000;"
  }
}

第二步

在 Hoa.EntityFramework.Core 层创建新的 DbContext,如 OtherDbContext:

using Microsoft.EntityFrameworkCore;

namespace Hoa.EntityFrameworkCore
{
    public partial class OtherDbContext : DbContext
    {
        public OtherDbContext(DbContextOptions<OtherDbContext> options)
            : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlServer("Name=OtherDatabase");
            }
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            OnModelCreatingPartial(modelBuilder);
        }

        partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
    }
}

第三步

在 Hoa.Web.Core.ServiceExtensions.HoaDbContextConfigureExtension 中配置新的 DbContext 信息:

using Hoa.EntityFrameworkCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace Hoa.Web.Core.ServiceExtensions
{
    public static class HoaDbContextConfigureExtension
    {
        public static IServiceCollection AddHoaDbContext(this IServiceCollection services, IWebHostEnvironment env)
        {
            services.AddDbContextPool<HoaDbContext>(options =>
            {
                options.UseSqlServer(AppGlobal.Configuration.GetConnectionString("HoaDatabase"));
                if (env.IsDevelopment())
                {
                    options/*.UseLazyLoadingProxies()*/
                                .EnableDetailedErrors()
                                .ConfigureWarnings(c => c.Log((RelationalEventId.CommandExecuting, LogLevel.Debug)));
                }
            }
            , poolSize: 128);
            
            // 配置 OtherDbContext
            services.AddDbContextPool<OtherDbContext>(options =>
            {
                options.UseSqlServer(AppGlobal.Configuration.GetConnectionString("OtherDatabase"));
                if (env.IsDevelopment())
                {
                    options/*.UseLazyLoadingProxies()*/
                                .EnableDetailedErrors()
                                .ConfigureWarnings(c => c.Log((RelationalEventId.CommandExecuting, LogLevel.Debug)));
                }
            }
            , poolSize: 128);

            return services;
        }
    }
}

第四步

在 Hoa.Core 层创建 OtherDbContextIdentifier 数据库上下文标识类,注意:必须以 Identifier 结尾!!!并继承 DbContextIdentifier 类。

using Hoa.DbManager.Identifiers;

namespace Hoa.Core
{
    public class OtherDbContextIdentifier : DbContextIdentifier
    {
        public OtherDbContextIdentifier() : base(nameof(OtherDbContextIdentifier))
        {
        }
    }
}

第五步

在 Hoa.EntityFrameworkCore.HoaEntityFrameworkCoreModule 中新增配置代码:

using Autofac;
using Hoa.DbManager.Identifiers;
using Microsoft.EntityFrameworkCore;

namespace Hoa.EntityFrameworkCore
{
    public class HoaEntityFrameworkCoreModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<HoaDbContext>()
                .As<DbContext>()
                .InstancePerLifetimeScope();

            builder.RegisterType<HoaDbContext>()
                .Named<DbContext>(nameof(HoaDbContextIdentifier))
                .InstancePerLifetimeScope();
            
            // 配置 OtherDbContext
            builder.RegisterType<OtherDbContext>()
                .Named<DbContext>(nameof(OtherDbContextIdentifier))
                .InstancePerLifetimeScope();
        }
    }
}

第六步

上述配置好后,可以通过 IDynamicRepository<TEntity,TDbContextIdentifier> 初始化了:

using Hoa.Core.Test.Entities;
using Hoa.Dependencies;
using Hoa.ServiceController.Attributes;
using Hoa.UnitOfWork.Repositories;
using System.ComponentModel.DataAnnotations;

namespace Hoa.Application.Test
{
    [HoaServiceController]
    public class TestAppService : ITestAppService, IAppServiceDependency
    {
        private readonly IRepository<TestEntity> _testRepository;
        
        // 初始化 OtherDbContext
        private readonly IDynamicRepository<TestEntity,OtherDbContextIdentifier> _testOtherRepository;
        
        public TestAppService(
            IRepository<TestEntity> testRepository
            // 在构造函数中注入
            , IDynamicRepository<TestEntity,OtherDbContextIdentifier> testOtherRepository;
            )
        {
            _testRepository = testRepository;
            
            // 使用
            _testOtherRepository = testOtherRepository;
        }

        // ... Other Codes
    }
}

关键代码

private readonly IDynamicRepository<TestEntity,OtherDbContextIdentifier> _testOtherRepository;

读写分离配置

文档整理中......

关于分布式事务

在多数据库操作上下文操作数据库中,默认开启了分布式事务(同一个服务器内的不同数据库),如果数据库操作上下文不在同一个服务器上将报错:

System.PlatformNotSupportedException: This platform does not support distributed transactions.

目前提供的解决方案是:在方法上面关闭分布式事务即可。

[UnitOfWork(false)]
上一页9.10、工作单元和事务下一页9.12、切面上下文(TangentDbContext)

最后更新于4年前

这有帮助吗?

那是因为 .NET Core 3.x 还,需要在 .NET 5.x 版本才支持。

不支持跨平台的分布式事务