Entity Framework unable to find connection string in nested web.config - c#

I'm new to .NET, but I'm using EntityFramework 5.0 and .NET 4.5
I have a website where the connectionStrings in the web.config are maintained in a configSource as follows:
<connectionStrings configSource="ConfigOverrides\overrideConnectionStrings.config">
</connectionStrings>
My website has modules with nested web.config files. These modules specify their own connectionStrings in the nested web.config. Everything was fine until I put a System.Data.EntityClient connection in my ConfigOverrides\overrideConnectionStrings file. After I did this I would get an error from the module:
No connection string named 'WebsiteEntities' could be found in the application config file.
If I copy the module's connectionString to the one in ConfigOverrides I get an error that there is already a connection string with that name. If I remove the connection string from their nested web.config and just put it in my overrides, it works. However I'm not wanting to maintain all module's connectionSettings in that global override.
Contents of overrideConnectionStrings.config:
<connectionStrings>
<add name="SqlServices" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=my_db;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\my_db.mdf;" />
<add name="TermsEntities" providerName="System.Data.EntityClient" connectionString="metadata=res://*/Terms.csdl|res://*/Terms.ssdl|res://*/Terms.msl;provider=System.Data.SqlClient;provider connection string='data source=(LocalDb)\v11.0;Initial Catalog=my_db;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\my_db.mdf;connect timeout=30;MultipleActiveResultSets=True;App=EntityFramework'" />
<add name="ADServer" connectionString="LDAP://ldap.localdomain:389/DC=company,DC=com" />
</connectionStrings>
Contents of module's nested Web.config connectionStrings:
<connectionStrings>
<add name="WebsiteEntities" connectionString="metadata=res://*/WSE.csdl|res://*/WSE.ssdl|res://*/WSE.msl;provider=System.Data.SqlClient;provider connection string="data source=.;initial catalog=WSE_DB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="RoutingConn" providerName="System.Data.SqlClient" connectionString="data source=.;initial catalog=WSE_DB;integrated security=True;" />
</connectionStrings>
I should note that the module worked fine until I added my TermsEntities to the main site's web.config (via the ConfigOverrides).

I am still unable to figure out what in my application setup is causing the connectionString to not be found. While debugging I could view the connectionStrings available to the path of the request and I would see all connectionStrings (those in the nested web.config and those in the root web.config).
My workaround is to just use the ConfigurationManager from System.Configuration and read in the connection string :
public partial class WebsiteEntities : DbContext
{
public WebsiteEntities()
: base(ConfigurationManager.ConnectionStrings["WebsiteEntities"].ConnectionString ?? "name=WebsiteEntities")
{
}
...
This seems to be working.

Related

EF code-first to create local database in ASP.NET MVC and C#

I am new to ASP.NET MVC. While going through this tutorial https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application
I am getting error
CREATE FILE encountered operating system error 123 (the filename, directory name, or volume label syntax is incorrect.) while attempting to open or create the physical file 'C:\Users\AMIT & AKASH\ContosoUniversity2 AttachDBFilename=|DataDirectory|_ContosoUniversity2.mdf.mdf'.
CREATE DATABASE failed. Some file names listed could not be created. Check related errors.
My connection string
<connectionStrings>
<add name="SchoolContext"
connectionString="Data Source=(LocalDb)\v12.0;Initial Catalog=ContosoUniversity2 AttachDBFilename=|DataDirectory|\ContosoUniversity2.mdf;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
SchoolInitializer.cs
StudentContext.cs
You most likely just forgot a semicolon after specifying the initial catalog:
<connectionStrings>
<add name="SchoolContext"
connectionString="Data Source=(LocalDb)\v12.0;Initial Catalog=ContosoUniversity2;AttachDBFilename=|DataDirectory|\ContosoUniversity2.mdf;Integrated Security=SSPI;"
providerName="System.Data.SqlClient" />
</connectionStrings>
So change:
Initial Catalog=ContosoUniversity2
to
Initial Catalog=ContosoUniversity2;
^
|
add this semicolon!

DbContext won't accept named connection string for LocalDb

I have app.config like this:
<connectionStrings>
<add name="MyDB" connectionString="Data Source=(localdb)\ProjectsV12;Initial Catalog=MrBoy;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False" />
</connectionStrings>
In my DbContext class, it works fine if I copy-paste the connection-string e.g.
: base("Data Source=(localdb)\ProjectsV12;Initial Catalog=MrBoy;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False")
But if I specify
:base("name=MyDB")
I get an error from my application and from the Package manager console:
"The connection string 'MyDB' in the application's configuration file
does not contain the required providerName attribute."
Why is a valid connection-string not accepted? Is there a workaround other than passing the connection-string manually into my constructor?
Do this
<add name="MyDB" connectionString="Data Source=(localdb)\ProjectsV12;Initial Catalog=MrBoy;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False" providerName="System.Data.SqlClient" />
Connectionstrings require a provider type. Setting it as entity context != defining the connection string. The type is assumed when you are setting context.

How to set connectionstring at web.config file programmatically or dynamically?

I'm trying to create an ASP.NET website. There I'm using a database. To connect with the database I'm using the connectionstring which I've stored in the web.config file like
<connectionStrings>
<add name="DBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=G:\CarRentalServices\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
</connectionStrings>
and at code behind
private string _connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
So you can see the database is stored at G:\path\to\db\CarRentalServiceDB.mdf.
But now if my friend want to take the project from me and try to run the project from his machine then he has to change the connectionString at web.config. Say the website is now at D:\path\to\db\foo\CarRentalServiceDB.mdf in my friend's machine, then the connectionString needs to change. Isn't it tedious?
Is there any way to change the connectionString dynamically with any batch file or code so that it will change with respect to the current directory it is residing now?
You shoud use the |DataDirectory| token: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.connectionstring.aspx
<connectionStrings>
<add name="DBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
You would add multiple connections strings in your web.config file and call the one you need like
Web.config File
<connectionStrings>
<add name="DBConnectionString"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=G:\CarRentalServices\App_Data\CarRentalServiceDB.mdf;Integrated Security=True"/>
<add name="DBConnectionStringTwo"
connectionString="Data Source=(LocalDB)\v11.0;AttachDbFilename=D:\path\to\db\foo\CarRentalServiceDB.mdf;Integrated Security=True"/>
</connectionStrings>
Code for connection strings
//Connection String 1
private string _connectionString = ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString;
//Connection String 2
private string _connectionString2 = ConfigurationManager.ConnectionStrings["DBConnectionStringTwo"].ConnectionString;

web.config transform - delete comments from connectionstring section

I store several different connection strings in my web.config for development and testing. All but one is commented out so I can change info as needed.
When I publish, I would like to replace everything (including comments) in the connectionStrings node with this:
<add name="myDb" connectionString="Data Source={SERVER};Initial Catalog=ManEx;User Id={USER};Password={PASSWORD};" providerName="System.Data.SqlClient" />
<!--<add name="myDb" connectionString="Data Source={SERVER};Initial Catalog=ManEx;Integrated Security=True" providerName="System.Data.SqlClient" />-->
I know how to change the active string with this:
<add name="myDb"
connectionString="Data Source={SERVER};Initial Catalog=ManEx;User Id={USER};Password={PASSWORD};"
providerName="System.Data.SqlClient"
xdt:Transform="Add"
xdt:Locator="Match(name)"/>
But I don't know how to clear out the comments I don't want and add the comment I do want.
Any ideas?
Instead of transforming the string, or using "Remove" and "Insert" clean the section try using "Replace".
For example:
<connectionStrings xdt:Transform="Replace">
<add name="myDb"
connectionString="Data Source={SERVER};Initial Catalog=ManEx;User Id={USER};Password={PASSWORD};"
providerName="System.Data.SqlClient" />
</connectionStrings>
You can configure this section exactly how you want it, even if that means you add new comments.
What I did based on this answer was the following:
Removed the existing connectStrings section in Web.config which contains commented out connection strings used during debug time;
Re-added the connectionStrings section with the correct connection string to be used when the app is deployed.
So in your Web.config transform file you have something like this:
<!-- Removes the existing connectionStrings section which contains internal connection strings used for debugging -->
<connectionStrings xdt:Transform="Remove">
</connectionStrings>
<!-- Re-adding the existing connectionStrings section -->
<connectionStrings xdt:Transform="Insert">
<add name="MyConnectionStringName" connectionString="Data Source=CLUSTERSQL;Initial Catalog=MyDatabase;Integrated Security=True;multipleactiveresultsets=True" providerName="System.Data.SqlClient" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
In Visual Studio 2013, you can have several Web.config files.
Also, when you create a new project, VS creates 2 for you : Web.Debug.config and Web.Release.config. That way, you can have a different Web.Config for your debug project and for your release project
If you need to Add/Insert/Setattributes inside a replaced connectionstring (for example if you use deployments) you can nest the transformations to remove the comments and replace the attributes:
<connectionStrings xdt:Transform="Replace">
<add name="connectionDatabase"
connectionString="#{ConnectionString}"
xdt:Transform="SetAttributes"
xdt:Locator="Match(name)" />
</connectionStrings>

c# Loading connectionString from file on runtime

I have an application (Console) already in place which is reading connection string from the bin directory.
We are planning to pass a directory path from command line which would point to the configurations.This way we would be able to switch between pointing to different DBs by just changing the command line parameter for "ConfigurationDirectory"
This requires us to dynamically load the connectionstring, the format of my connection string is as below :
<connectionStrings>
<add name="DB1" connectionString="Data Source=DB;Initial Catalog=someCatalog;Persist Security Info=True;User ID=****;Password=****; Asynchronous Processing=true" providerName="System.Data.SqlClient" />
<add name="DB2" connectionString="Data Source=DBName;Initial Catalog=someCatalog2;Persist Security Info=True;User ID=****;Password=****; Asynchronous Processing=true" providerName="System.Data.SqlClient" />
</connectionStrings>
We do not have a configuration tag.
To load up the connection string dynamically I am trying this :
var connectionStringconfigfile = "C:Somepath\connectionstring.config"
ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = connectionStringconfigfile;
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("connectionStrings");
I am unable to use the connectionstring file I have currently because it complains that there is no configuration tag.
The problem is that my code already uses the following to initialize connection string :
ConfigurationManager.ConnectionStrings["DB1"].ConnectionString
With this new approach the above line does not seem to work and always gives me null, is there a way so that I do not have to change my existing code?
If you wrap your external config file in a <configuration> block, like this:
<configuration><br>
<connectionStrings><br>
<add name="DB1" connectionString="Data Source=DB;Initial Catalog=someCatalog;Persist Security Info=True;User ID=****;Password=****; Asynchronous Processing=true" providerName="System.Data.SqlClient" /><br>
<add name="DB2" connectionString="Data Source=DBName;Initial Catalog=someCatalog2;Persist Security Info=True;User ID=****;Password=****; Asynchronous Processing=true" providerName="System.Data.SqlClient" /><br>
</connectionStrings><br>
</configuration>
Your code should work.

Categories

Resources