Linq to SQL支持SQL Server
話說Linq to SQL支持SQL Server等多種數據庫的,而且應該支持多種數據庫,到最后卻落的這個局面,是為了商業考慮還是本來技術就不成熟?不得而知。不過不管怎么說Linq to SQL的體系結構確實是支持擴展的。
在System.Data.Linq.Mapping這個命名空間下微軟提供了一個特性:ProviderAttribute,使用強類型的DataContext或使用Xml做映射的時候,該特性可以用來指定具體的數據庫提供者。如下:
- [Database(“dbo.cnblogs”)]
- [Provider(typeof(SqlProvider))]
- Public CnBlogDataContext : DataContext
- {
- }
這就表明我們的Linq to SQL支持SQL Server數據庫了,SqlProvider是實現了IProvider接口的(該接口存在于System.Data.Linq.Provider命名空間下)。
在DataContext初始化時執行的Init方法里有這樣幾行代碼:
- if (model.ProviderType == null)
- {
- throw Error.ProviderTypeNull();
- }
- Type providerType = model.ProviderType;
- if (!typeof(IProvider).IsAssignableFrom(providerType))
- {
- throw Error.ProviderDoesNotImplementRequiredInterface(providerType,
- typeof(IProvider));
- }
- this.provider = (IProvider) Activator.CreateInstance(providerType);
- this.provider.Initialize(this.services, connection);
請注意的是,實際的Linq to SQL支持SQL Server,所以類圖描述的關系并不存在,但是我們從代碼中完全可以想象的到即使要擴展也是很容易的,這就是架構的力量,即使是昨天的設計也能應付明天的變化。
關于Provider的初始化就介紹到這里了,在文章末尾的源代碼下載里提供了IProvider類和SqlProvider類,你可以看看初始化的過程,并想想如何構建一個可擴展的架構。
【編輯推薦】