W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
WTM框架支持自動(dòng)選擇讀寫分離的數(shù)據(jù)庫(kù),以及根據(jù)條件動(dòng)態(tài)使用不同的數(shù)據(jù)庫(kù)連接
讀寫分離- "ConnectionStrings": [
- {
- "Key": "default",
- "Value": "Server=(localdb)\\mssqllocaldb;Database=demo;Trusted_Connection=True;MultipleActiveResultSets=true"
- },
- {
- "Key": "default_1",
- "Value": "Server=(localdb)\\mssqllocaldb;Database=demo1;Trusted_Connection=True;MultipleActiveResultSets=true"
- },
- {
- "Key": "default_2",
- "Value": "Server=(localdb)\\mssqllocaldb;Database=demo2;Trusted_Connection=True;MultipleActiveResultSets=true"
- },
- {
- "Key": "default_3",
- "Value": "Server=(localdb)\\mssqllocaldb;Database=demo3;Trusted_Connection=True;MultipleActiveResultSets=true"
- },
- ]
-
這個(gè)配置文件定義了四個(gè)連接字符串,default是寫庫(kù),default_1,default_2,default_3是三個(gè)只讀庫(kù)
框架會(huì)默認(rèn)在所有標(biāo)記了HttpPost的Controller方法中使用寫庫(kù)來(lái)創(chuàng)建DataContext,而在其他方法中隨機(jī)選擇一個(gè)讀庫(kù)
如果框架的默認(rèn)實(shí)現(xiàn)不能滿足需求,可以使用FixConnection屬性來(lái)指定連接字符串,比如下面的Controller
- [FixConnection(DBOperationEnum.Read, CsName = "test")]
- [HttpPost]
- public IActionResult Create()
- {
- var testDc = this.DC;
- return PartialView();
- }
-
通過在方法上加FixConnection,我們指定這個(gè)方法里的DC應(yīng)該使用連接字符串是test開頭的只讀庫(kù),框架會(huì)去尋找比如test_1,test_2,test_3...這種key值的連接字符串,如果找不到就會(huì)使用叫test的連接字符串,如果仍然找不到,則會(huì)使用默認(rèn)的default
另一種指定連接字符串的方法是不使用Controller和VM中已經(jīng)生成的DC,而是直接使用指定連接字符串新實(shí)例化一個(gè)DataContext,比如
- [HttpPost]
- public IActionResult Create()
- {
- var testDc = new DataContext("test_2");
- return PartialView();
- }
以上代碼指定使用key值為test_2的連接字符串來(lái)創(chuàng)建一個(gè)新的DataContext
框架可以根據(jù)頁(yè)面?zhèn)鬟f過來(lái)的數(shù)據(jù),或者session里的信息等動(dòng)態(tài)選擇需要連接的數(shù)據(jù)庫(kù),請(qǐng)看以下代碼
- public class Program
- {
- public static void Main(string[] args)
- {
- BuildWebHost(args).Run();
- }
- public static IWebHost BuildWebHost(string[] args) =>
- WebHost.CreateDefaultBuilder(args)
- .ConfigureServices(x =>
- {
- x.AddFrameworkService(CsSector: CSSelector);
- x.AddLayui();
- })
- .Configure(x =>
- {
- x.UseFrameworkService();
- })
- .Build();
- public static string CSSelector(ActionExecutingContext context)
- {
- var userinfo = (context.Controller as BaseController).LoginUserInfo;
- if(userinfo == null)
- {
- return "default";
- }
- else
- {
- if (userinfo.ITCode.StartsWith("a"))
- {
- return "user1";
- }
- else
- {
- return "user2";
- }
- }
- }
- }
-
上面的代碼將一個(gè)用于選擇連接字符串的函數(shù)傳給了AddFrameworkService,這個(gè)函數(shù)根據(jù)當(dāng)前登錄用戶來(lái)選擇使用的數(shù)據(jù)庫(kù)。沒有登陸時(shí)用default,用戶名以a開頭時(shí)用user1庫(kù),其他用user2庫(kù)
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: