目錄索引
【無私分享:ASP.NET CORE 項目實戰】目錄索引
簡介
增加對多資料庫的支援,并不是意味着同時對多種資料庫操作,當然,後面,我們會嘗試同時對多種資料庫操作,這可能需要多個上下文,暫且不論。分布式資料庫,我們采用的是阿裡雲的Mycat,這個後面會更新出來。我們今天的場景是:我們的項目可能是在windows上開發的使用的是SqlServer,我們要釋出到linux上,SqlServer 2017 據說是支援liunx的,但是還沒出... 當然不是說 SqlServer 就不能裝在liunx上,但是我們的Liunx伺服器可能已經安裝了MySql或 Oracle,我們希望使用現有的,又或者是,我們需要切換資料庫。那麼,我們需要可以随時切換資料庫的支援。
添加NuGet包,注冊服務
使用SqlServer資料庫,這個官方有詳細的步驟和解釋,可以參考:https://docs.efproject.net/en/latest/providers/sql-server/index.html ,我們簡單介紹一下
在 【(第四章)】Code First 建立資料庫和資料表 中,我們使用的就是SqlServer,我們建立了一個資料上下文 ApplicationDbContext ,
然後在 Startup.cs 的 ConfigureServices(IServiceCollection services) 中,我們作為一個服務注冊了上下文對象:
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("SqlServerConnection")));
在使用 UseSqlServer() 的時候,我們在 project.json 中添加了依賴包:Microsoft.EntityFrameworkCore.SqlServer
那麼,如何添加對Mysql的支援呢,在2016年8月24日,Mysql 官方出了第一版對 EntityFrameworkCore 支援的依賴包 (MySql.Data.EntityFrameworkCore 7.0.4-IR-191),這個我第一時間就嘗試過,有少許問題,因為剛出,資料非常少,也幾乎沒多少用過的,也可能是有Bug,也可能是我自身的原因,不管什麼原因,我還是一直用 官方沒出之前的 第三方的依賴,今天,我們就是用 這個 依賴包作為示範,當然,大家可以使用官方的,對于使用,因為我們使用的是EF,是以在操作上沒什麼太大的差別,也可以随時切換。
首先,我們引入這個包 Pomelo.EntityFrameworkCore.MySql,NuGet:Install-Package Pomelo.EntityFrameworkCore.MySql
使用非常簡單,跟上面的 SqlServer 一樣,我們注冊上下文(Startup.cs):
services.AddDbContext<ApplicationDbContext>(options => options.UseMySql(Configuration.GetConnectionString("MySqlConnection")));
對了,就是把 UseSqlServer()改成 UseMySql()
Oracle的官方也沒出,也沒發現很好的第三方,我們這裡就先不介紹了,等養肥了。
修改配置檔案,實作切換
我們上面實作了 EntityFrameworkCore 對兩種資料庫的支援,那麼,我們總不能每次切換資料庫都要 修改 Startup.cs 再編譯生成吧,我們應該做一個類似開關之類的,可以實作釋出完成的項目的資料庫的切換。
這裡,我用的是配置檔案。
我們在 【(第八章)】讀取配置檔案(二) 讀取自定義配置檔案 中介紹了,如何使用自定義配置檔案 siteconfig.json
并且我們寫了一個讀取自定義配置檔案的方法 GetAppSettings<T>(string key),這個方法,我稍微做了修改,增加了一個參數,可以讀取任意的自定義配置檔案,同時增加了對集合的讀取(MyCat分布式資料庫的時候讀取節點會用到),這裡把修改後的給大家貼一下:
public class AppConfigurtaionServices
{
/// <summary>
/// 擷取自定義配置檔案配置
/// </summary>
/// <typeparam name="T">配置模型</typeparam>
/// <param name="key">根節點</param>
/// <param name="configPath">配置檔案名稱</param>
/// <returns></returns>
public T GetAppSettings<T>(string key,string configPath= "siteconfig.json") where T:class,new()
{
IConfiguration config = new ConfigurationBuilder()
.Add(new JsonConfigurationSource { Path= configPath, ReloadOnChange=true })
.Build();
var appconfig= new ServiceCollection()
.AddOptions()
.Configure<T>(config.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions<T>>()
.Value;
return appconfig;
}
/// 擷取自定義配置檔案配置(異步方式)
public async Task<T> GetAppSettingsAsync<T>(string key, string configPath = "siteconfig.json") where T : class, new()
.Add(new JsonConfigurationSource { Path = configPath, ReloadOnChange = true })
.Build();
var appconfig = new ServiceCollection()
return await Task.Run(() => appconfig);
public List<T> GetListAppSettings<T>(string key, string configPath = "siteconfig.json") where T : class, new()
.AddOptions()
.Configure<List<T>>(config.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions<List<T>>>()
.Value;
public async Task<List<T>> GetListAppSettingsAsync<T>(string key, string configPath = "siteconfig.json") where T : class, new()
.AddOptions()
.Configure<List<T>>(config.GetSection(key))
.BuildServiceProvider()
.GetService<IOptions<List<T>>>()
.Value;
}
我們修改一下我們的配置檔案siteconfig.json :添加一個資料庫選擇的配置

我們在平台檢測類(沒有的也可以自己建立一個)中,增加一個類用于檢測資料庫配置:internal class DataBaseProvider { }
我們通過我們上面的讀取配置檔案的方法 讀取 我們的配置:
private ApplicationConfiguration dataBaserProvider = new Services.ConfigServices.AppConfigurtaionServices().GetAppSettings<ApplicationConfiguration>("siteconfig");
讀取資料庫類型:
public bool _isSqlServer
{
get
{
return dataBaserProvider.DataBase.ToLower() == "mssql";
}
}
public bool _isMySql
return dataBaserProvider.DataBase.ToLower() == "mysql";
public bool _isOracle
return dataBaserProvider.DataBase.ToLower() == "oracle";
好了,我們回到我們的 Startup.cs:
首先,我們執行個體化一下我們這個類:
修改 ConfigureServices(IServiceCollection services) 方法的 上下文注冊服務:
OK,這樣我們就很簡陋的實作了切換,我們來測試一下:
首先使用SqlServer:siteconfig.json : "DataBase": "MSSQL"
dotnet ef database update
使用MySql:siteconfig.json : "DataBase": "MYSQL"
好了,到這裡就結束了,雖然簡陋,給大家提供一下思路。
希望跟大家一起學習Asp.net Core
剛開始接觸,水準有限,很多東西都是自己的了解和翻閱網上大神的資料,如果有不對的地方和不了解的地方,希望大家指正!
雖然Asp.net Core 現在很火熱,但是網上的很多資料都是前篇一律的複制,是以有很多問題我也暫時沒有解決,希望大家能共同幫助一下!
原創文章 轉載請尊重勞動成果 http://yuangang.cnblogs.com