2012-12-31 47 views
2

我在Visual Studio Express 2012中爲Web簡單CRUD Web應用程序(庫)創建學校項目。我從這個很好的教程啓發 - http://www.asp.net/mvc/tutorials/mvc-music-store/mvc-music-store-part-1SQL Server Compact - 連接到SDF數據文件

現在我有連接到SQL Server精簡版.sdf數據文件的問題。

web.config我有這樣的連接字符串:

<connectionStrings> 
    <add name="LibraryEntities" 
    connectionString="Data Source=C:\Users\Administrator\Documents\Visual Studio 2012\Projects\2OBOP3_KU1\R10491\App_Data\R10491_library.sdf;" 
    providerName="System.Data.SqlServerCe.4.0"/> 
    </connectionStrings> 

我創建簡單的ASPX文件的數據庫連接測試:

<script runat="server"> 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["LibraryEntities"].ToString())) 
     { 
      SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM Writers", cn); 
      cn.Open(); 
      SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
      rdr.Read(); 
      Response.Write(rdr[0].ToString()); //read a value 
     } 
    } 
</script> 

當我運行一個應用程序,它拋出一個異常:

Exception Details: System.Data.SqlClient.SqlException: 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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

但是當我嘗試連接到我的.sdf fil e在「數據庫資源管理器」菜單的「數據庫資源管理器」選項卡中(「解決方案資源管理器」旁邊)我成功連接。

所以我假設連接字符串應該有問題 - 是不是?感謝您的建議。

回答

4

您正在連接到SQL Server Compact而不是SQL Server。

您應該使用SqlCeConnection而不是SqlConnection

using System.Data.SqlServerCe; 

    protected void Page_Load(object sender, EventArgs e) 
    { 
     using (SqlCeConnection cn = new SqlCeConnection(ConfigurationManager.ConnectionStrings["LibraryEntities"].ToString())) 
     { 
      SqlCeCommand cmd = new SqlCeCommand("SELECT COUNT(*) FROM Writers", cn); 
      cn.Open(); 
      SqlCeDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
      rdr.Read(); 
      Response.Write(rdr[0].ToString()); //read a value 
     } 
    } 

你也需要有system.data.sqlserverce.dll

參考
相關問題