EntityFramework實現多資料來源動態切換

2021-10-25 01:26:38 字數 2780 閱讀 3610

做專案的時候一般是乙個鏈結乙個庫,但是有時候碰上分庫的需求場景,比如saas模式,a租戶資料存在a資料庫,b租戶資料存在b資料庫。那怎麼來實現資料來源的動態、靈活的切換呢?下面我們就來看看怎麼實現。

1、 web.config配置資料庫連線串

2、注入connectionservice

//依客戶切換連線registerscope(builder.registertype().as().withparameter("sourceconnectionstring", conn.bqool_service).keyed(connectiontype.bqool_service));
3、 獲取動態生成的資料庫鏈結

public class connectionschdbservice : iconnectionservicepublic string getdbconnectionstring(string account = null)return setconnection(account, isconnectui);}public string getservername(string account = null)return null;}public string getservicename(string account = null)return null;}public void setconnectionui(bool isconnectui)private string setconnection(string account, bool isconnectui = false)//連線到 account_service_rel_historyvar accountservicerel = getaccountservicerelhistory(account);if (accountservicerel != null)if (!system.environment.userinteractive && system.web.httpcontext.current == null) //windows service, isconnectui:, conn:");}return returnconnection;}
public inte***ce iconnectionserviceprivate string _defaultconnectionstring;private dbcontext _dbcontext;private sqlconnection _sqlconnection;private string _account;private string _servername;private string _servicename;public dbcontext getdbcontext(string account = null)if (_dbcontext == null || isresetconnection)type t = typeof(dbcontext);_dbcontext =(dbcontext)activator.createinstance(t, _defaultconnectionstring);}return _dbcontext;}
5 、根據得到的上下文鏈結sqlconnection ,訪問資料庫

protected string _servicenameprotected string _userprotected sqlconnection _conn}//private void setdbcontextfactory(idbcontextfactory factory)//_conn = factory.getsqlconnection();_servername = factory.getservername();_servicename = factory.getservicename();_user = factory.getuser();}protected void create(string sql, object data)1、動態生成訪問鏈結

2、定義訪問的上下文dbcontext

3、連上資料庫操作

Entity Framework 架構簡介

當微軟的wcf 大行其道,通用資料訪問模型entity framework卻稍遜一籌,有很多需要完善和進步的地方,本文對entity framework 架構做一下簡介。實體框架 entitry framework 以下簡稱ef 看起來像乙個有趣的技術,更強大,比linq to sql 更先進。這兩...

entity framework 批量刪除

以前用sql寫批量刪除的時候,感覺挺利索的,簡潔地寫了 public bool delectusersuggest string addsql 然後在頁面層直接呼叫 現在用entity framework,感覺有點麻煩不能直接delete,還要先把資料查出來,以下是主要 1 先查出實體 region...

Entity Framework 動態查詢

不想多說什麼直接說 region 搜尋並分頁 ljy 傳入搜尋條件,當前頁碼,每頁的顯示的條數,資料的總數 輸出引數 三個引數,返回 商實體 搜尋條件 當前頁碼 每頁的顯示的條數 資料的總數 public iqueryable endregion 在頁面呼叫時如果通過時間來查詢,請記住一定要這樣寫 ...