2013-01-24 106 views
2

我需要驗證DataContext對象上的ConnectionString屬性,以確保LINQ可以獲得與數據庫的連接。我已經嘗試了下面兩種方法,但是,如果連接字符串無效,它們會鎖定應用程序。 LINQ有沒有另外一種方法來做到這一點?如何測試Linq-to-SQL連接字符串以確保其有效

public static bool TestDBConnection(connectionString) 
    { 
     bool result = true; 
     DomainClassesDataContext db = new DomainClassesDataContext(connectionString); 

     try 
     { 
      // Hangs if connectionString is invalid rather than throw an exception 
      db.Connection.Open(); 

      // Initially, I was just trying to call DatabaseExists but, this hangs as well if the conn string is invalid 
      if (!db.DatabaseExists()) 
      { 
       result = false; 
      } 
     } 
     catch (Exception ex) 
     { 
      result = false; 
      logger.Fatal(ex.Message); 
      logger.Fatal(ex.StackTrace); 
     } 
     finally 
     { 
      db.Dispose(); 
     } 

     return result; 
    } 
+2

它真的是_hang_還是隻是倒計時的連接超時? –

+0

啊,可能就是這樣。我現在將檢查... – Grasshopper

+0

超時設置爲0,但是,我無法弄清楚如何更改它,因爲該屬性上只有一個setter。 – Grasshopper

回答

1

將連接字符串中的Connection Timeout設置爲像5s這樣的低值。

開幕是不夠的。您可能會收到一個陳舊的聯網連接。執行查詢:SELECT NULL

+1

這最終是它最終成爲的。另一個應用程序正在生成此應用程序正在使用的連接字符串,並在連接字符串中將其設置爲0。我最終不得不解析將連接字符串替換爲5s並在DataContext上進行更改。 – Grasshopper