在我們的項目中我們有時候需要在我們的項目中創建DbContext,而且這些DbContext之間有明顯的界限,比如系統中兩個DbContext一個是和整個數據庫的權限相關的內容而另外一個DbContext則主要是和具體業務相關的內容,這兩個部分彼此之間可以分開,那么這個時候我們就可以在我們的項目中創建兩個不同的DbContext,然后分別注入進去,當然這兩個DbContext可以共用一個ConnectionString,也可以分別使用不同的DbContext,這個需要根據不同的需要來確定,在我們建立完了不同的DbContext的時候,我們就需要分別將每一個DbContext修改的內容遷移到數據庫里面去,這個就涉及到數據庫Migration的問題了,所以整篇文章主要圍繞如何創建多個DbContext和每個DbContext的Migration的問題。
下面我們通過代碼來創建兩個不同的DbContext
1 創建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());
// 請在此處填寫所有與具體數據庫無關的 Model 調整,確保單元測試可以覆蓋
if (Database.IsInMemory())
return;
}
}
這個DbContext主要用來做一些和身份驗證以及權限相關的操作,這里只是定義了一個最簡單的結構,后面的一個DbContext就是具體業務相關的內容,在我們的項目中,我們兩個DbContext會使用相同的連接字符串。
2 IDesignTimeDbContextFactory接口實現
/// <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配置的連接字符串。
{
"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中調用下面的代碼,這個是有所不同的地方,具體我們來看看代碼。
// 初始化 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,並遷移數據庫整個過程。
