简体   繁体   中英

ASP.net Database connection to remote SQL server DB not in 'App_Data'

New to the ASP.NET world. My default connection string in 'Web.config' (Visual Studio 2013) is initially connected to a local db as:

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-dbTest-20141022090046.mdf;Initial Catalog=aspnet-dbTest-20141022090046;Integrated Security=True" providerName="System.Data.SqlClient"/>

I have been reading about connections to remote servers (SQL Express). I was able to modify the default connection string to the following:

<add name="DefaultConnection" connectionString="Data Source=MYSERVERNAME\SQLEXPRESS;
  Initial Catalog=myDatabase;
  Integrated Security=True;
  User ID=MYUSERNAMEISDIFFERENT;
  Password=MYUSERPASSWORDISDIFFERENT"
  providerName="System.Data.SqlClient"/>

The internal tables (non ASP.NET) are not available as objects to interact with and I do not see the database as a resource in the 'App_Data' folder.
Is this normal?
Should I include something "AttachDbFileName=|DataDirectory|" ?

I can connect and log in (I do see the login and new 'user' account inside MS SQLServer Management Studio in the database after it builds the ASP.Net tables.

Andy

You want to access the connection string using the configuration manager:

var connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;

This can then be used in a database connection such as:

var dt = new DataTable();
using (var con = new SqlConnection(connectionString))
{
    var command = new SqlCommand("SELECT * FROM table", con);

    con.Open();
    dt = command.ExecuteQuery();
}

'dt' will be filled with the results of the query provided to the SqlCommand object

There are other ways to connect, but generally this way is the simplest to get going with.

Sam's Answer worked for me...

However, As in anything I find that knowing the right term and or word makes the process so much easier.

The approach that all of the online training I have been going through was "Code First" examples. The way that I am trying to take the information I have learned is this. That I want to go to "Database First"

This link outlined everything that I wanted to do: http://www.asp.net/mvc/tutorials/mvc-5/database-first-development/creating-the-web-application

That is that I have Visual Studio 2013, and an existing database (AdventureWorks 2012) in SQLServerExpress.

Thanks again, and I hope the link helps someone..

Andy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM