2015-09-07 64 views
1

我尝试了一切,但我无法获得连接到数据库的基本asp.net站点。我正在使用Visual Studio并试图从本地数据库文件中检索数据到.cshtml页面上的表中。将asp.net网站连接到本地数据库.mdf文件以检索数据时遇到问题

我试图访问的数据库位于App_Data文件夹中。

在Web.config文件我已经下连接字符串如下:

<add name="connectionName" connectionString="Data Source=|DataDirectory|\database.mdf" providerName="System.Data.SqlClient"/> 

在页面本身我有:

@{ 
var DB = Database.Open("connectionName"); 
var selectQueryString = "SELECT * FROM Clients ORDER BY lastName"; 
} 

<table> 
    <thead> 
     <tr> 
      <td>client_id</td> 
      <td>firstName</td> 
      <td>lastName</td> 
      <td>address</td> 
      <td>city</td> 
      <td>state</td> 
      <td>postalCode</td> 
      <td>phone</td> 
     </tr> 
    </thead> 
    @foreach (var row in DB.Query(selectQueryString)) 
    { 
    <tr> 
     <td>@row.client_id</td> 
     <td>@row.firstName</td> 
     <td>@row.lastName</td> 
     <td>@row.address</td> 
     <td>@row.city</td> 
     <td>@row.state</td> 
     <td>@row.postalCode</td> 
     <td>@row.phone</td> 
    </tr> 
    } 
</table> 

正被抛出的异常是:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code 

我也看到一些文字说明问题可能是:

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)

回答

0

对于在你的MDF文件App_data目录,你需要包括AttachDbFilename属性如文件名和数据库正在运行设置data source属性到当地的是版本的本地数据源。它应该看起来像这样。

<add name="connectionName" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-myapp-mydb.mdf;Initial Catalog=aspnet-myapp-mydb;Integrated Security=True" providerName="System.Data.SqlClient" /> 
+0

非常感谢您的意见。看起来这是朝着正确的方向前进,但现在我看到了另一个例外。 在System.Data.dll中发生类型'System.Data.SqlClient.SqlException'的异常,但未在用户代码中处理 附加信息:由于数据库的版本是782,因此无法打开数据库'数据库'。此服务器支持版本706和更早版本。降级路径不受支持。 由于我使用Visual Studio来创建.mdf文件并运行该程序,我该如何更改正在使用的服务器版本? –

0

NM。我想我需要改变(LocalDB)\ v11.0到(LocalDB)\ MSSQLLocalDB没有更多的版本782错误。非常感谢你的帮助! Padhraic让我疯狂!