简体   繁体   中英

Using web.config connection string in data access project

I'm on .NET 4.6.1, Visual Studio 2015, SQL Server Developer 2016. I want to specify my EF connection string in my main project's web.config, but I cannot for the life of me figure out how to reference that in my data access project. Every answer I can find says to do the same as in this one --that is, use this:

System.Configuration.ConfigurationManager
    .ConnectionStrings["connectionStringName"].ConnectionString;

When I use that, however, the valid connection string isn't being passed. It's instead getting one that appears to be the default; the data source is being set to .\\SQLEXPRESS when I have no string with that defined anywhere. Searching all files in the solution for SQLEXPRESS returns no results, so it's not hardcoded anywhere.

What is the correct way to pass my connection string from my main web.config (with the relevant transforms per build) to my data access project?

There is only one app.config / web.config that will be read from at run time and that is the config associated with the applications entry point. So if you have a web project and a referenced project that serves at the data access layer and you want to read a connection string from the config the web.config of the web project is used. The same is true for a windows application or wpf etc, only the applications main entry point's configuration will be used. Once your application is running you can reference that app.config / web.config from anywhere in your code though as you generally do this using string identifiers.

In other words if you have a project with your Data Access compiled to MyDA.dll and you app.config in that project that might be output to MyDA.dll.config ( this does not happen by default ) anything you have in MyDA.dll.config is ignored at runtime. The file will not be read from, only the web.config will be used OR the app.config of the .exe 's entry point.


For Entity Framework's DbContext you can pass the name of the connection string directly to the constructor. You do not have to retrieve the connection string and pass it yourself. So give each connection a specific unique name in your web.config.

<connectionStrings>
    <add name="ConnectionName1" connectionString="Data Source=(local);Database=YourDB;User Id=YourUser;Password=yourPassword" providerName="System.Data.SqlClient" />
    <add name="ConnectionName2" connectionString="Data Source=(local);Database=YourDB2;User Id=YourUser2;Password=yourPassword2" providerName="System.Data.SqlClient" />
    <!-- more here -->
</connectionStrings>

Then in your code you can create your Entity Framework's DbContext using that name.

var myEntities = new MyEntities("ConnectionName1"); // MyEntities is some class that derives from DbContext

In my past projects the DbContext I work with usually always maps to one database at run time. What I mean here is I would not use the same DbContext type multiple times pointing to different databases. In this case I hard code that name right into my DbContext type and make sure that my consuming applications have that connection name listed in the web.config or app.config respectively.

public class MyEntities : DbContext {
    public MyEntities() : base("ConnectionName1") {}
}

// calling code now never has to know about the connection
using(var myEntities = new MyEntities()) { /* do something here */}

Alternatively if you really do want the complete connection element you can reference System.Configuration ( add it to your project references in the project where you make the following call ) and call it this way.

var connection = System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionName1"];
var conString = connection.ConnectionString; // you can also get the provider
var myEntities = new MyEntities(conString);

I have not used this approach in a while but maybe there is a good reason to use it in your case.

The data source is being set to .\\SQLEXPRESS when I have no string with that defined anywhere. Searching all files in the solution for SQLEXPRESS returns no results, so it's not hardcoded anywhere.

Its hardcoded in your machine config file. Simply add:

<clear />

Above your first connection string to remove it.

You could remove the .\\SQLExpress connection string from line 126 in the machine.config, however IMHO play on the safe side and dont mess with machine config, preferring to use <clear /> instead.

Have you tried connection to the Server Explorer -> Data Connections and having the property auto generated? Next thing I would tried is adding an ADO.Net data model and pointing to the correct DB with the Access driver. It may be as simple as provider on the configuration string.

Here is a simplified example and/or proper way given by MSDN:

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

config file like the following:

  <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <startup> 
            <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
        </startup>
        <connectionStrings>
          <add name="connectionStringName" connectionString="Data Source=(LocalDB)\v11.0;Initial Catalog=DatabaseName;Integrated Security=True;Pooling=False" />
        </connectionStrings>
    </configuration>

Needed namespaces:

System.Configuration

From : https://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings(v=vs.110).aspx

As far as I remember, when using EF, it creates a connection string that matches the name of the context you defined, so, if your context is named MyContext then you should define a connection string with that name in your app/web.config . To save you the trouble of writing the EF connection string on your own (which is much longer than a regular ADO.Net connection string), just copy the one that was generate in the DLLs .config file.

Once you have that, you can use the configuration transformation functionality built into web projects, that allows you to change portions of the .config file depending on the current build configuration, for example:

  • web.config - Will hold the DEVELOPMENT connection string.
  • web.staging.config - will hold a replace transformation with the STAGING connection string.
  • web.release.config - will hold a replace transformation with the RELEASE connection string.

Hope it helps!

 <configuration>
    <connectionStrings>
      <add name="CONNECTIONSTRINGNAME" connectionString="server=.; Database=YOURDATABASENAME;Integrated Security=true;" providerName="System.Data.SqlClient"/>
    </connectionStrings>
 </configuration>

change the capital letters with your own data

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