標籤:
WebMatrix之WebMatrix.Data
WebMatrix資料訪問系列目次:
- WebMatrix之資料訪問
- WebMatrix之WebMatrix.Data
- WebMatrix之WebMatrix.Data揭密
- WebMatrix之改革WebMatrix.Data
在 上篇文章中,我簡單形貌了在WebMatrix web開闢東西怎樣簡單的實現資料庫的CRUD。其中,資料庫訪問組件WebMatrix.Data是微軟專為WebMatrix打造的一個輕量型的動態 資料訪問組件。你可以通過單獨引用WebMatrix.Data.dll步伐集,來作為資料訪問的輕量型組件。之以是說是輕量型的,由於該組件不付出儲存 進程,事物,說到底,它就是專為SSCE量身打造的。
下面簡單來看看WebMatrix.Data是怎樣跨資料庫平台事變的。
1.SQL Server 2005/2008的付出
以 往神馬跨資料庫付出的大家見得最多的莫過於三層中的通過更換DAL的dll,工場模式連合設定檔案依靠注入實現資料庫的切換。但是 WebMatrix.Data如今完全不必要那麼做,最簡單的方法是通過設定檔案設定節ConnectionString具體設定即可。下例是利用的一個 控制台步伐,在app.config下的ConnectionString如下:
<connectionStrings><add name="mysqldb" connectionString="Server=.;Database=MyTestDb;User ID=sa;Password=******;" providerName="System.Data.SqlClient"/></connectionStrings>
設定檔案設定好後你可以像如許訪問資料:
//sql server var db = Database.Open("
上述代碼雷同訪問SSCE資料庫一樣,差別之處在於必要提供相應資料庫的設定毗連字號串,DataBase.Open要領傳入一個定名的毗連字號串“mysqldb”。
必要留意的是假如省略connectionStrings中的providerName,將會拋出非常:
但是可以在AppSettings中這麼來寫來防備非常的拋出從而正常訪問資料庫:
<appSettings> <add key="systemData:defaultProvider" value=http://www.cnblogs.com/Microred/archive/2012/04/04/"System.Data.SqlClient"/> </appSettings>
假 如既不在connectionStrings中提供providerName,也不在AppSettings中設定providerName,那麼 WebMatrix.Data會預設利用SSCE的SQL提供步伐(System.Data.SqlServerCe.4.0)。至於為什麼,下篇文章將 會揭秘。
同樣地,可以利用DataBase.OpenConnectionString(string connectionString)及其重載要領OpenConnectionString(string connectionString, string providerName)傳入一個未定名的毗連字號串來建立一個DataBase執行個體。
2.Oracle的付出
Oracle的測試我選用了ODP.NET(Oracle Data Provider for .net)。期間,發明白一個問題(利用了一個偷懶的寫法),假如connectionStrings像如許設定:
<add name="myoracle" connectionString="Data Source=ORADB;User ID=testdb;Password=*****;" providerName="Oracle.DataAccess.Client" />
ORADB是在tnsnames.ora設定的,利用傳統的方法沒有任何問題:
var data = http://www.cnblogs.com/Microred/archive/2012/04/04/new DataTable(); using (OracleConnection connection = new OracleConnection(connectionstring)) { using (OracleDataAdapter adapter = new OracleDataAdapter("SELECT * FROM testdb.SYS_DICT a", connection)) { adapter.Fill(data); } }
但是利用WebMatrix.Data訪問就會有問題:
var db = Database.Open("myoracle"); var list = db.Query("SELECT * FROM testdb.SYS_DICT a"); foreach (var item in list) { Console.WriteLine(item.DICT_NAME); }TAG:之webWebMatrix
WebMatrix之WebMatrix.Data