How to link to a SQL Server database from an ASP.NET webpage?

Step 1. Create the SQL Server database and the table. Please note the database file does not have to be in the App_Data folder of the ASP.NET Project folder (But for the compact edition database in WebMatrix, the sdf file needs to be in this folder). It can be in the normal data folder for SQL Server, such as:

D:\Program Files\Microsoft SQL Server\MSSQL10_50.R2\MSSQL\DATA

Step 2. In VS, configure the connection string in the web.config file as below:
<configuration>
       <connectionStrings>
             <add name="myconnectionstring" connectionString="Server=MachineName\InstanceName;  Database=SmallBakery4;User ID=YourWindowsLogin;Password=YourWindowsPW;Trusted_Connection=True;" providerName="System.Data.SqlClient"/>
       </connectionStrings>
       <system.web>
             <compilation debug="true">
             </compilation>
       </system.web>
</configuration>

Step 3. In VS, in the cshtml file, use Database.Open('myconnectionstringname') to open the database:
@{
    //var db = Database.Open("SmallBakery"); use this option if using compact edition in WebMatrix
    var db = Database.Open("myconnectionstring"); //defined in the web.confog file
    var query = "SELECT * FROM Product";
}
<html>
<body>
    <h1>Small Bakery Products</h1>
    <table border="1" width="70%">
        <tr>
            <th>Id</th>
            <th>Product</th>
            <th>Description</th>
            <th>Price</th>
        </tr>
        @foreach (var row in db.Query(query))
        {
            <tr>
                <td>@row.Id</td>
                <td>@row.Name</td>
                <td>@row.Description</td>
                <td align="right">@row.Price</td>
            </tr>
        }
    </table>
</body>
</html>

Step 4. In VS, no need to manually "Add Connection" in Data Connections. When you run the code, VS will automatically create one "myconnectionstring (WebSite1(1))", defaulted to closed. Webite1(1) is the name for the WebSite.

Step 5. Also notice, there is no database file in the C:\Users\Charlie\Documents\Visual Studio 2012\WebSites\WebSite1\App_Data folder,neither in the App_Data folder in VS (The two should represent the same information).

Step 6. If you face error message on LINQ in the temporary ASP.NET files, delete these temp cs files in the corresponding Net Framework folder.



Step 7. Press Ctr+A to select the cshtml code, then press Ctrl+Shift+W to process it. Enjoy the cakes!