zoukankan      html  css  js  c++  java
  • Asp.Net Core中创建多DbContext并迁移到数据库

    Asp.Net Core中创建多DbContext并迁移到数据库

     

      在我们的项目中我们有时候需要在我们的项目中创建DbContext,而且这些DbContext之间有明显的界限,比如系统中两个DbContext一个是和整个数据库的权限相关的内容而另外一个DbContext则主要是和具体业务相关的内容,这两个部分彼此之间可以分开,那么这个时候我们就可以在我们的项目中创建两个不同的DbContext,然后分别注入进去,当然这两个DbContext可以共用一个ConnectionString,也可以分别使用不同的DbContext,这个需要根据不同的需要来确定,在我们建立完了不同的DbContext的时候,我们就需要分别将每一个DbContext修改的内容迁移到数据库里面去,这个就涉及到数据库Migration的问题了,所以整篇文章主要围绕如何创建多个DbContext和每个DbContext的Migration的问题。 

      下面我们通过代码来创建两个不同的DbContext

      1 创建AuthorityDbContext

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public class AuthorityDbContext : AbpZeroDbContext<Tenant, Role, User, AuthorityDbContext> {
            /* Define a DbSet for each entity of the application */
     
            public DbSet<UserMapping> UserMappings { getset; }
     
            public SunlightDbContext(DbContextOptions<SunlightDbContext> options)
                base(options) {
            }
     
            protected override void OnModelCreating(ModelBuilder modelBuilder) {
                base.OnModelCreating(modelBuilder);
                modelBuilder.ApplyConfiguration(new TenantConfiguration());
     
                // 请在此处填写所有与具体数据库无关的 Model 调整,确保单元测试可以覆盖
     
                if (Database.IsInMemory())
                    return;           
            }
            
        }

      这个DbContext主要用来做一些和身份验证以及权限相关的操作,这里只是定义了一个最简单的结构,后面的一个DbContext就是具体业务相关的内容,在我们的项目中,我们两个DbContext会使用相同的连接字符串。

      2 IDesignTimeDbContextFactory接口实现

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    /// <summary>
       /// 用于 EF Core Migration 时创建 DbContext,数据库连接信息来自 XXX.Dcs.WebHost 项目 appsettings.json
       /// </summary>
       public class AuthorityDesignTimeDbContextFactory : IDesignTimeDbContextFactory<AuthorityDbContext> {
           private const string DefaultConnectionStringName = "Default";
     
           public SunlightDbContext CreateDbContext(string[] args) {
               var configuration = AppConfigurations.Get(WebContentDirectoryFinder.CalculateContentRootFolder());
               var connectString = configuration.GetConnectionString(DefaultConnectionStringName);
     
               var builder = new DbContextOptionsBuilder<SunlightDbContext>();
               builder.UseSqlServer(connectString);
               return new SunlightDbContext(builder.Options);
           }
       }

      在了解这段代码之前,你可以先了解一下这个到底是做什么用的,就像注释里面说的,当我们使用EFCore Migration的时候,这里会默认读取WebHost项目里面的appsettings.json里面的Default配置的连接字符串。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    {
      "ConnectionStrings": {
        "Default""Server=XXXX,XX;Database=XXXX;User Id=XXXX;Password=XXXX;",
        "DcsEntity""Server=XXXX,XX;Database=XXXX;User Id=XXXX;Password=XXXX;"
      },
      "Redis": {
        "Configuration""127.0.0.1:XXXX",
        "InstanceName""XXXX-Sales"
      },
      "App": {
        "ServerRootAddress""http://localhost:XXXX/",
        "ClientRootAddress""http://localhost:XXXX/",
        "CorsOrigins""http://localhost:XX,http://localhost:XX,http://localhost:XX"
      },
      "Kafka": {
        "BootstrapServers""127.0.0.1:XX",
        "MessageTimeoutMs": 5000,
        "Topics": {
          "CustomerAndVehicleEvent""XXXX-customer-update",
          "AddOrUpdateProductCategoryEvent""XXXX-add-update-product-category",
          "AddOrUpdateDealerEvent""XXXX-add-update-dealer",
          "ProductUpdateEvent""XXXX-product-update",
          "VehicleInformationUpdateStatusEvent""XXXX-add-update-vehicle-info",
          "AddCustomerEvent""cowin-add-customer"
        }
      },
      "Application": {
        "Name""XXXX-sales"
      },
      "AppSettings": {
        "ProductSyncPeriodMi": 60,
        "DealerSyncPeriodMi": 60
      },
      "Eai": {
        "Authentication": {
          "Username""2XXX2",
          "Password""XXXX"
        },
        "Services": {
          "SapFinancial""http://XXXX:XXXX/OSB_MNGT/Proxy/XXXX"
        }
      },
      "DependencyServices": {
        "BlobStorage""http://XXXX-XXXX/"
      },
      "Authentication": {
        "JwtBearer": {
          "IsEnabled"true,
          "Authority""http://XXXX/",
          "RequireHttpsMetadata"false
        }
      },
      "Sentry": {
        "IncludeRequestPayload"true,
        "SendDefaultPii"true,
        "MinimumBreadcrumbLevel""Debug",
        "MinimumEventLevel""Warning",
        "AttachStackTrace"true
      },
      "Logging": {
        "LogLevel": {
          "Default""Warning"
        }
      }
    }

      3 DB Migration

      有了上面的工作之后,我们就能够进行数据库迁移并更新到数据库了,主要过程分为2步Add-Migration XXX和Update-Database -verbose两步,只不过是现在我们想构建多个DbContext,所以我们需要通过参数-c xxxDbContext来指定具体的DbContext ,否则会报下面的错误。More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.

      有了这些以后,我们就可以更新到数据库了,在更新的时候记住要指定DbContext,更新时使用下面的命令:Update-Database -verbose -c XXXDbContext。

      4 创建第二个DbContext

      有了前面的过程,创建第二个DbContext的过程就比较简单了,重复上面的步骤一、二、三,然后完成第二个DbContext的创建和数据库的迁移,但是这里我们需要注意一些不同之处,第一个由于我们想要使用ABP框架中的多租户相关的一些实体,所以这里我们构建的基类是继承自AbpZeroDbContext,后面我们创建的业务相关的DbContext的时候,我们不需要这些,所以我们只需简单继承自AbpDbContext即可。

      5 Startup中初始化EF Core DbContext

      这个和之前创建一个DbContext有所不同的是我们需要向Asp.Net Core依赖注入容器中两次注入不同的DbContext,在Asp.Net Core中该如何创建DbContext并实现注入,请点击这里参考官方文档,在这里我们需要在Startup中的ConfigureServices中调用下面的代码,这个是有所不同的地方,具体我们来看看代码。 

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    // 初始化 EF Core DbContext
                var abpConnectionString = _appConfiguration.GetConnectionString("Default");
                services.AddDbContext<SunlightDbContext>(options => {
                    options.UseSqlServer(abpConnectionString);
                    if (Environment.IsDevelopment()) {
                        options.EnableSensitiveDataLogging();
                        // https://docs.microsoft.com/en-us/ef/core/querying/client-eval#optional-behavior-throw-an-exception-for-client-evaluation
                        options.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
                    }
                });
                // AuthConfigurer.MapUserIdentity 需使用 DbContextOptions<SunlightDbContext>
                // Abp DI 未自动注册该对象,故而特别处理
                services.AddTransient(provider => {
                    var builder = new DbContextOptionsBuilder<SunlightDbContext>();
                    builder.UseSqlServer(abpConnectionString);
                    return builder.Options;
                });
                var dcsConnectionString = _appConfiguration.GetConnectionString("DcsEntity");
                services.AddDbContext<DcsDbContext>(options => {
                    options.UseSqlServer(dcsConnectionString);
                    if (Environment.IsDevelopment()) {
                        options.EnableSensitiveDataLogging();
                        // https://docs.microsoft.com/en-us/ef/core/querying/client-eval#optional-behavior-throw-an-exception-for-client-evaluation
                        options.ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
                    }
                }); 

      这样就能够在服务具体运行的过程中来添加具体的DbContext啦,经过上面的过程我们就能够实现在一个项目中添加多个DbContext,并迁移数据库整个过程。

  • 相关阅读:
    乱码问题
    play之路由 routes
    delphi之http通讯
    delphi之socket通讯
    Delphi之ComboBox
    delphi 常用函数
    字节
    EXCEPT
    V_REPORT_AOC_FUEL]
    相同表结构不同记录
  • 原文地址:https://www.cnblogs.com/zxtceq/p/13718817.html
Copyright © 2011-2022 走看看