Asp.Net Core中創(chuàng)建多DbContext并遷移到數(shù)據(jù)庫的步驟
在我們的項目中我們有時候需要在我們的項目中創(chuàng)建DbContext,而且這些DbContext之間有明顯的界限,比如系統(tǒng)中兩個DbContext一個是和整個數(shù)據(jù)庫的權(quán)限相關(guān)的內(nèi)容而另外一個DbContext則主要是和具體業(yè)務(wù)相關(guān)的內(nèi)容,這兩個部分彼此之間可以分開,那么這個時候我們就可以在我們的項目中創(chuàng)建兩個不同的DbContext,然后分別注入進去,當然這兩個DbContext可以共用一個ConnectionString,也可以分別使用不同的DbContext,這個需要根據(jù)不同的需要來確定,在我們建立完了不同的DbContext的時候,我們就需要分別將每一個DbContext修改的內(nèi)容遷移到數(shù)據(jù)庫里面去,這個就涉及到數(shù)據(jù)庫Migration的問題了,所以整篇文章主要圍繞如何創(chuàng)建多個DbContext和每個DbContext的Migration的問題?!?/p>
下面我們通過代碼來創(chuàng)建兩個不同的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());
// 請在此處填寫所有與具體數(shù)據(jù)庫無關(guān)的 Model 調(diào)整,確保單元測試可以覆蓋
if (Database.IsInMemory())
return;
}
}
這個DbContext主要用來做一些和身份驗證以及權(quán)限相關(guān)的操作,這里只是定義了一個最簡單的結(jié)構(gòu),后面的一個DbContext就是具體業(yè)務(wù)相關(guān)的內(nèi)容,在我們的項目中,我們兩個DbContext會使用相同的連接字符串。
2 IDesignTimeDbContextFactory接口實現(xiàn)
/// <summary>
/// 用于 EF Core Migration 時創(chuàng)建 DbContext,數(shù)據(jù)庫連接信息來自 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
有了上面的工作之后,我們就能夠進行數(shù)據(jù)庫遷移并更新到數(shù)據(jù)庫了,主要過程分為2步Add-Migration XXX和Update-Database -verbose兩步,只不過是現(xiàn)在我們想構(gòu)建多個DbContext,所以我們需要通過參數(shù)-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.
有了這些以后,我們就可以更新到數(shù)據(jù)庫了,在更新的時候記住要指定DbContext,更新時使用下面的命令:Update-Database -verbose -c XXXDbContext。
4 創(chuàng)建第二個DbContext
有了前面的過程,創(chuàng)建第二個DbContext的過程就比較簡單了,重復(fù)上面的步驟一、二、三,然后完成第二個DbContext的創(chuàng)建和數(shù)據(jù)庫的遷移,但是這里我們需要注意一些不同之處,第一個由于我們想要使用ABP框架中的多租戶相關(guān)的一些實體,所以這里我們構(gòu)建的基類是繼承自AbpZeroDbContext,后面我們創(chuàng)建的業(yè)務(wù)相關(guān)的DbContext的時候,我們不需要這些,所以我們只需簡單繼承自AbpDbContext即可。
5 Startup中初始化EF Core DbContext
這個和之前創(chuàng)建一個DbContext有所不同的是我們需要向Asp.Net Core依賴注入容器中兩次注入不同的DbContext,在Asp.Net Core中該如何創(chuàng)建DbContext并實現(xiàn)注入,請點擊這里參考官方文檔,在這里我們需要在Startup中的ConfigureServices中調(diào)用下面的代碼,這個是有所不同的地方,具體我們來看看代碼。
// 初始化 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));
}
});
這樣就能夠在服務(wù)具體運行的過程中來添加具體的DbContext啦,經(jīng)過上面的過程我們就能夠?qū)崿F(xiàn)在一個項目中添加多個DbContext,并遷移數(shù)據(jù)庫整個過程。
以上就是Asp.Net Core中創(chuàng)建多DbContext并遷移到數(shù)據(jù)庫的步驟的詳細內(nèi)容,更多關(guān)于Asp.Net Core創(chuàng)建多DbContext并遷移到數(shù)據(jù)庫的資料請關(guān)注腳本之家其它相關(guān)文章!
- 在.NetCore(C#)中使用ODP.NET Core+Dapper操作Oracle數(shù)據(jù)庫
- 淺談如何使用vb.net從數(shù)據(jù)庫中提取數(shù)據(jù)
- asp.net實現(xiàn)存儲和讀取數(shù)據(jù)庫圖片
- .NET Core Dapper操作mysql數(shù)據(jù)庫的實現(xiàn)方法
- C# Ado.net實現(xiàn)讀取SQLServer數(shù)據(jù)庫存儲過程列表及參數(shù)信息示例
- ASP.NET Core2讀寫InfluxDB時序數(shù)據(jù)庫的方法教程
- ASP.NET WebAPI連接數(shù)據(jù)庫的方法
- .net core利用orm如何操作mysql數(shù)據(jù)庫詳解
- .net core下配置訪問數(shù)據(jù)庫操作
- .net數(shù)據(jù)庫操作框架SqlSugar的簡單入門
相關(guān)文章
asp.net錯誤捕獲(錯誤處理)page_error事件使用方法
Page_Error事件提供了一種捕獲頁面級錯誤的方法。對于錯誤的處理,您可以只是顯示錯誤信息(正如下面的示例代碼所示),也可以記錄事件或執(zhí)行某個其他操作2014-01-01
.Net Core和jexus配置HTTPS服務(wù)方法
下面小編就為大家分享一篇.Net Core和jexus配置HTTPS服務(wù)方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02
Net Core全局配置讀取管理方法ConfigurationManager
這篇文章主要為大家詳細介紹了Net Core全局配置讀取管理方法ConfigurationManager的相關(guān)資料,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-08-08
Automation服務(wù)器不能創(chuàng)建對象的多種解決辦法
這篇文章主要介紹了Automation服務(wù)器不能創(chuàng)建對象的多種解決辦法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-01-01
ASP.NET The system cannot find the file specified解決辦法
這篇文章主要介紹了ASP.NET The system cannot find the file specified解決辦法的相關(guān)資料,需要的朋友可以參考下2016-11-11

