2011-08-17 64 views
0

我用2個數據庫的EF - 與SQL CE和SQL Server。我正在使用SQL CE或SQL Server的實體框架?

有沒有辦法知道在運行時使用哪種連接類型?我的意思是,如果我在某個地方只有ObjectContext(已經用一些連接字符串初始化),我可以從中獲取數據庫類型(目前是Compact還是SQL Server)?

感謝

+0

EF4(或至少一個)的要點是要抽象這個信息。如果你能夠從上下文中推斷出哪個數據庫正在使用,我強烈建議不要從中形成任何邏輯? – Smudge202

+0

謝謝,我現在談論這個。根據這個,只有一個Timeout setter。我希望能夠重做它。但我現在需要一個小小的修復:) – Shaddix

回答

3

您可以檢查Connection Property,它應該返回一個EntityConnection;從那裏你必須檢查它的StoreConnection這將是「真正的」數據庫連接。

從那裏,你可以檢查ConnectionString,它會告訴你的供應商,或者只需檢查供應商連接本身的類型isGetType。如果它是SQL Server,它將是一個SqlConnection,如果它是SQL CE,它將是一個SqlCeConnection

這看起來像一個醜陋的黑客,因爲它是;如果你正在尋找一種方法來做到這一點沒有醜陋的黑客,不要打擾 - ObjectContext明確設計而不是泄漏有關連接的任何信息,除非你確切知道要問什麼。相比之下,這裏的一切,你將不得不通過跳躍通過應用程序配置,以檢查它的籃球:

static string GetProviderName(ObjectContext context) 
{ 
    string entityConnectionString = GetEntityConnectionString(context); 
    return !string.IsNullOrEmpty(entityConnectionString) ? 
     GetProviderConnectionString(entityConnectionString) : null; 
} 

static string GetEntityConnectionString(ObjectContext context) 
{ 
    var match = Regex.Match(context.Connection.ConnectionString, 
     @"name=(?<name>[^;]+)", RegexOptions.Compiled); 
    string connectionStringName = match.Success ? 
     match.Groups["name"].Value : null; 
    return ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString; 
} 

static string GetProviderConnectionString(string entityConnectionString) 
{ 
    var match = Regex.Match(entityConnectionString, 
     @"provider=(?<provider>[^;]+)", RegexOptions.Compiled); 
    return match.Success ? match.Groups["provider"].Value : null; 
} 

一旦任何解決方案開始涉及正則表達式,我傾向於找一個彎路,在這種情況下,這就是你說你不想使用的類型。選擇你的毒藥。

要小心如何使用上述任何一種方法。 EF4的設計大約是持續性無知,你應該試圖避免任何特定於連接類型的邏輯,因爲你真的不知道它將如何配置(也許明天它將是Oracle連接)。我相信特定於提供者的代碼主要位於QueryProvider

+0

感謝您的回答和關於持久性無知的提醒 - 一切都會好起來的:) ConnectionString沒有用 - 在我的情況下它只是「name = SomeSpecificName」。我現在正在使用你的第二個提議,但Connection屬性的類型是'DbConnection',現在我將它轉換爲'EntityConnection',如:((EntityConnection)(Connection))。StoreConnection是SqlCeConnection' 。這是我想擺脫的事情,如果有另一種方式:) – Shaddix

相關問題