How do I connect to an .mdf (Microsoft SQL Server Database File) in a simple web project?

Question!

Specifically, in VS 2008, I want to connect to a data source that you can have by right-clicking on the automatically-generated App_Data folder (an .mdf "database"). Seems easy, and it is once you know how.



Answers

In your Login.aspx.cs (the code behind file for your login page in the submit button click event) add

string constr = @"Data Source=(LocalDB)\v11.0; AttachDbFilename=|DataDirectory|\myData.mdf; Integrated Security=True; Connect Timeout=30;";
using (SqlConnection conn = new SqlConnection(constr))
string constr =    ConfigurationManager.ConnectionStrings["myData"].ToString();

using (SqlConnection conn = new SqlConnection(constr))
{
sqlQuery=" Your Query here"
SqlCommand com = new SqlCommand(sqlQuery, conn);
com.Connection.Open();
string strOutput = (string)com.ExecuteScalar();
}
By : Sudheesh


So here's the answer from MSDN:

Choos[e] "Add New Data Source" from the Data menu.[And follow the connection wizard]

Very easy, except that I have no Data menu. If you don't have a Data menu, do the following:

  • Click on Tools >> Connect to Database...
  • Select "Microsoft SQL Server Database File", take the default Data provider, and click OK
  • On the next screen, browse to your Database file, which will be in your VS Solution folder structure somewhere.

Test the connection. It'll be good. If you want to add the string to the web.config, click the Advanced button, and copy the Data Source line (at the bottom of the dialog box), and paste it into a connection string in the appropriate place in the web.config file. You will have to add the "AttachDbFilename" attribute and value. Example:

The raw text from the Advanced panel:

Data Source=.\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;User Instance=True

The actual entry in the web.config:

<add name="SomeDataBase" connectionString="Data Source=.\SQLEXPRESS; 
AttachDbFilename=C:\Development\blahBlah\App_Data\SomeDataFile.mdf;
Integrated Security=True; Connect Timeout=30; User Instance=True" />


<add name="Your Database" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Expanse.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=True&quot;" providerName="System.Data.EntityClient"/>
By : Spice


This video can help you solving your question :)
By: admin