2010-04-06 59 views
0

我正在嘗試從類庫項目中訪問數據庫。在App.config文件我都連接字符串,像這樣定義網絡相關或特定於實例的錯誤

add name="EditRegionConnectionString" connectionString="Data Source=.\SQLExpress;Initial Catalog=testdb;Integrated Security=True" 
      providerName="System.Data.SqlClient" 

我試圖通過代碼訪問此conenction串

Table<cont> table1 = new DataContext("EditRegionConnectionString").GetTable<cont>(); 
var t1 = from t in table1 select t; 
//i am getting error here 
t1.FirstOrDefault(); 

錯誤

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

回答

1

您需要實際使用連接字符串,而不僅僅是它的名字。嘗試類似:

string conString = ConfigurationManager 
         .ConnectionStrings["EditRegionConnectionString"] 
         .ConnectionString; 

Table<cont> table1 = new DataContext(conString).GetTable<cont>();