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,然后分別注入進去,當(dāng)然這兩個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); } }
在了解這段代碼之前,你可以先了解一下這個到底是做什么用的,就像注釋里面說的,當(dāng)我們使用EFCore Migration的時候,這里會默認(rèn)讀取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)文章
GridView導(dǎo)出Excel實現(xiàn)原理與代碼
使用GridView來展示數(shù)據(jù)庫表,幾乎沒對GridView的格式做什么設(shè)定,從配置文件中加載SQL,跑出數(shù)據(jù)就直接綁定到GridView,接下來介紹導(dǎo)出Excel的功能感興趣的朋友可以參考下2013-01-01asp.net Javascript獲取CheckBoxList的value
最近在做一個BS的小項目,記得自己搞asp.net的時候,還是兩年以前,大部分的東西只是有點印象,忘得差不多了,所以這次也算是溫習(xí)的過程吧,一邊學(xué)習(xí),一邊趕工,呵呵呵。。。。2009-12-12C#實現(xiàn)EXCEL數(shù)據(jù)到TXT文檔的轉(zhuǎn)換
C#實現(xiàn)EXCEL數(shù)據(jù)到TXT文檔的轉(zhuǎn)換,需要的朋友可以參考一下2013-02-02ASP.NET中的Inherits、CodeFile、CodeBehind的區(qū)別詳解
這篇文章主要介紹了ASP.NET中的Inherits、CodeFile、CodeBehind的區(qū)別詳解,需要的朋友可以參考下2014-07-07asp.net下將頁面內(nèi)容導(dǎo)入到word模板中的方法
asp.net下將頁面內(nèi)容導(dǎo)入到word模板中的方法,需要的朋友可以參考下。2010-10-10Asp.net內(nèi)置對象之Cookies(簡介/屬性方法/基本操作及實例)
本文將圍繞cookies了解Cookies對象/Cookie對象的屬性和方法/Cookie的基本操作及實例:Cookie的寫入和讀取/Cookie對象相比Session、Application的優(yōu)缺點扥等,感興趣的朋友可以了解下,或許對你學(xué)習(xí)cookies有所幫助2013-02-02