欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Asp.Net Core中創(chuàng)建多DbContext并遷移到數(shù)據(jù)庫的步驟

 更新時(shí)間:2021年03月05日 16:49:50   作者:Hello 尋夢者!  
這篇文章主要介紹了Asp.Net Core中創(chuàng)建多DbContext并遷移到數(shù)據(jù)庫的步驟,幫助大家更好的理解和學(xué)習(xí)使用Asp.Net Core,感興趣的朋友可以了解下

  在我們的項(xiàng)目中我們有時(shí)候需要在我們的項(xiàng)目中創(chuàng)建DbContext,而且這些DbContext之間有明顯的界限,比如系統(tǒng)中兩個(gè)DbContext一個(gè)是和整個(gè)數(shù)據(jù)庫的權(quán)限相關(guān)的內(nèi)容而另外一個(gè)DbContext則主要是和具體業(yè)務(wù)相關(guān)的內(nèi)容,這兩個(gè)部分彼此之間可以分開,那么這個(gè)時(shí)候我們就可以在我們的項(xiàng)目中創(chuàng)建兩個(gè)不同的DbContext,然后分別注入進(jìn)去,當(dāng)然這兩個(gè)DbContext可以共用一個(gè)ConnectionString,也可以分別使用不同的DbContext,這個(gè)需要根據(jù)不同的需要來確定,在我們建立完了不同的DbContext的時(shí)候,我們就需要分別將每一個(gè)DbContext修改的內(nèi)容遷移到數(shù)據(jù)庫里面去,這個(gè)就涉及到數(shù)據(jù)庫Migration的問題了,所以整篇文章主要圍繞如何創(chuàng)建多個(gè)DbContext和每個(gè)DbContext的Migration的問題。 

  下面我們通過代碼來創(chuàng)建兩個(gè)不同的DbContext

  1 創(chuàng)建AuthorityDbContext

public class AuthorityDbContext : AbpZeroDbContext<Tenant, Role, User, AuthorityDbContext> {
        /* Define a DbSet for each entity of the application */
 
        public DbSet<UserMapping> UserMappings { get; set; }
 
        public SunlightDbContext(DbContextOptions<SunlightDbContext> options)
            : base(options) {
        }
 
        protected override void OnModelCreating(ModelBuilder modelBuilder) {
            base.OnModelCreating(modelBuilder);
            modelBuilder.ApplyConfiguration(new TenantConfiguration());
 
            // 請(qǐng)?jiān)诖颂幪顚懰信c具體數(shù)據(jù)庫無關(guān)的 Model 調(diào)整,確保單元測試可以覆蓋
 
            if (Database.IsInMemory())
                return;           
        }
        
    }

  這個(gè)DbContext主要用來做一些和身份驗(yàn)證以及權(quán)限相關(guān)的操作,這里只是定義了一個(gè)最簡單的結(jié)構(gòu),后面的一個(gè)DbContext就是具體業(yè)務(wù)相關(guān)的內(nèi)容,在我們的項(xiàng)目中,我們兩個(gè)DbContext會(huì)使用相同的連接字符串。

  2 IDesignTimeDbContextFactory接口實(shí)現(xiàn)

/// <summary>
   /// 用于 EF Core Migration 時(shí)創(chuàng)建 DbContext,數(shù)據(jù)庫連接信息來自 XXX.Dcs.WebHost 項(xiàng)目 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);
       }
   }

  在了解這段代碼之前,你可以先了解一下這個(gè)到底是做什么用的,就像注釋里面說的,當(dāng)我們使用EFCore Migration的時(shí)候,這里會(huì)默認(rèn)讀取WebHost項(xiàng)目里面的appsettings.json里面的Default配置的連接字符串。

{
  "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

  有了上面的工作之后,我們就能夠進(jìn)行數(shù)據(jù)庫遷移并更新到數(shù)據(jù)庫了,主要過程分為2步Add-Migration XXX和Update-Database -verbose兩步,只不過是現(xiàn)在我們想構(gòu)建多個(gè)DbContext,所以我們需要通過參數(shù)-c xxxDbContext來指定具體的DbContext ,否則會(huì)報(bào)下面的錯(cuò)誤。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.

  有了這些以后,我們就可以更新到數(shù)據(jù)庫了,在更新的時(shí)候記住要指定DbContext,更新時(shí)使用下面的命令:Update-Database -verbose -c XXXDbContext。

  4 創(chuàng)建第二個(gè)DbContext

  有了前面的過程,創(chuàng)建第二個(gè)DbContext的過程就比較簡單了,重復(fù)上面的步驟一、二、三,然后完成第二個(gè)DbContext的創(chuàng)建和數(shù)據(jù)庫的遷移,但是這里我們需要注意一些不同之處,第一個(gè)由于我們想要使用ABP框架中的多租戶相關(guān)的一些實(shí)體,所以這里我們構(gòu)建的基類是繼承自AbpZeroDbContext,后面我們創(chuàng)建的業(yè)務(wù)相關(guān)的DbContext的時(shí)候,我們不需要這些,所以我們只需簡單繼承自AbpDbContext即可。

  5 Startup中初始化EF Core DbContext

  這個(gè)和之前創(chuàng)建一個(gè)DbContext有所不同的是我們需要向Asp.Net Core依賴注入容器中兩次注入不同的DbContext,在Asp.Net Core中該如何創(chuàng)建DbContext并實(shí)現(xiàn)注入,請(qǐng)點(diǎn)擊這里參考官方文檔,在這里我們需要在Startup中的ConfigureServices中調(diào)用下面的代碼,這個(gè)是有所不同的地方,具體我們來看看代碼。 

// 初始化 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 未自動(dòng)注冊(cè)該對(duì)象,故而特別處理
            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));
                }
            }); 

  這樣就能夠在服務(wù)具體運(yùn)行的過程中來添加具體的DbContext啦,經(jīng)過上面的過程我們就能夠?qū)崿F(xiàn)在一個(gè)項(xiàng)目中添加多個(gè)DbContext,并遷移數(shù)據(jù)庫整個(gè)過程。

以上就是Asp.Net Core中創(chuàng)建多DbContext并遷移到數(shù)據(jù)庫的步驟的詳細(xì)內(nèi)容,更多關(guān)于Asp.Net Core創(chuàng)建多DbContext并遷移到數(shù)據(jù)庫的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評(píng)論