Asp.Net Core中創(chuàng)建多DbContext并遷移到數(shù)據(jù)庫的步驟
在我們的項(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)文章!
- 在.NetCore(C#)中使用ODP.NET Core+Dapper操作Oracle數(shù)據(jù)庫
- 淺談如何使用vb.net從數(shù)據(jù)庫中提取數(shù)據(jù)
- asp.net實(shí)現(xiàn)存儲(chǔ)和讀取數(shù)據(jù)庫圖片
- .NET Core Dapper操作mysql數(shù)據(jù)庫的實(shí)現(xiàn)方法
- C# Ado.net實(shí)現(xiàn)讀取SQLServer數(shù)據(jù)庫存儲(chǔ)過程列表及參數(shù)信息示例
- ASP.NET Core2讀寫InfluxDB時(shí)序數(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實(shí)現(xiàn)原理與代碼
使用GridView來展示數(shù)據(jù)庫表,幾乎沒對(duì)GridView的格式做什么設(shè)定,從配置文件中加載SQL,跑出數(shù)據(jù)就直接綁定到GridView,接下來介紹導(dǎo)出Excel的功能感興趣的朋友可以參考下2013-01-01.Net?Core讀取文件時(shí)中文亂碼問題的解決方法分享
所以關(guān)于讀取文件亂碼的問題,百度上有很多方案,這里再給大家總結(jié)下,這篇文章主要給大家介紹了關(guān)于.Net?Core讀取文件時(shí)中文亂碼問題的解決方法,需要的朋友可以參考下2022-02-02asp.net Javascript獲取CheckBoxList的value
最近在做一個(gè)BS的小項(xiàng)目,記得自己搞asp.net的時(shí)候,還是兩年以前,大部分的東西只是有點(diǎn)印象,忘得差不多了,所以這次也算是溫習(xí)的過程吧,一邊學(xué)習(xí),一邊趕工,呵呵呵。。。。2009-12-12C#實(shí)現(xiàn)EXCEL數(shù)據(jù)到TXT文檔的轉(zhuǎn)換
C#實(shí)現(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)置對(duì)象之Cookies(簡介/屬性方法/基本操作及實(shí)例)
本文將圍繞cookies了解Cookies對(duì)象/Cookie對(duì)象的屬性和方法/Cookie的基本操作及實(shí)例:Cookie的寫入和讀取/Cookie對(duì)象相比Session、Application的優(yōu)缺點(diǎn)扥等,感興趣的朋友可以了解下,或許對(duì)你學(xué)習(xí)cookies有所幫助2013-02-02