How to load EF connection string from App.config after made it? - c#

I have problem and can't find solution.
On start I have that App.config file:
...
<connectionStrings>
<add name="IdealsadEntities" connectionString="" providerName="System.Data.EntityClient" />
</connectionStrings>
...
In my application (WinForm) I read params for connection to database from xml file and then override App.config and got compiled file AppName.exe.config.
Problem is with creating instance of my entities. I used this code after creating file:
IdealsadEntities _db = new IdealsadEntities();
But in first run application _db.Database.Connection is null. In second run it reading from AppName.exe.config file and works fine.
Questions:
So my question is why first runing read empty string even if I
rewrite this file?
Is DbContext execute earlier?
How to fix it, to get new connection string from rewrited file?

Your app.config is only read upon application startup. Changes you write to it during the runtime of your application will not be noticed until you restart the program.
You can however construct your entities using a connectionstring, like this:
IdealsadEntities _db = new IdealsadEntities("metadata=res://...");
Where you replace the appropriate info in the connectionstring by the data you read from the other file.

Related

No connection string named could be found in the application config file

I'm using EF and generated .EDMX from it but then I only wanted it to be used for automated generation of Class Files.
I then used the Class Files to create a Entity Model and then created a DB Context and then Repository. I'm calling a WebApi (which is in a separate project but same solution) to access the repository to GET data. While I run the WebApi, I'm getting the error,
{"No connection string named 'DBEntities' could be found in the application config file."}
But within my DAL, I have a webConfig and that has the following entry so I'm not quite sure what has gone wrong,
add name="DBEntities" connectionString="metadata=res://*/Models.DBModel.csdl|res://*/Models.DBModel.ssdl|res://*/Models.DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MY-PC;initial catalog=DB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient"
In the DBContext file, remove
public RaficaDB()
: base("name=DefaultConnection"){}
to
public RaficaDB()
: base("DefaultConnection"){}
EF 4.3, EF 5 and EF 6 do not like the connection string being called name=xxxxx
Answer found here -> No connection string named 'MyApplicationEntities' could be found in the application config file
You say "within my DAL, I have a webConfig". I guess the connection string is in the configuration file of a referenced class library, but not in the main configuration file you have in your entry project (a web api project, I guess looking at the tags).
If so, just copy the connection string in the entry project configuration file.
Insert following section in the configuration section of the .config file of the same project where your .edmx file is under.
You may also create different connection string for different environment in the .config file of the main project and pass any of the connection string as parameter of the constructor of the DBContext.
<connectionStrings>
<add name="DBEntities" connectionString="metadata=res://*/Models.DBModel.csdl|res://*/Models.DBModel.ssdl|res://*/Models.DBModel.msl;provider=System.Data.SqlClient;provider connection string="data source=MY-PC;initial catalog=DB;integrated security=True;multipleactiveresultsets=True;application name=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
Setting the project as Startup project worked for me
I found that this worked:
1) Check if you have several "App.config" files.
2) Check if has a wrong name than the connection string it has to use.
3) Save the project and run the program
It should work now.
Copy and paste the connectionstring to your WEBAPI Project web.config file will solve the issue.
It's dumb, but I had this error that was fixed by a Rebuild All !!
Might as well have turned it off and on again....
If none of the above fixes the issue, then probably you are doing the mistake I did, here was my case:
I have multiple projects in my solution and the Startup project was different than the one having the entity framework, switching project from the package manager console seems like a buggy thing especially in entity framework commands, so here what I did:
Set your webapi(Or the project has the entity framework) as a startup project.
Rebuild the solution and try again.
Run the entity framework command again.
If the above doesn't work then try to close the solution and try from Step 2, this should fix it.
The easiest solution:
Remove current edmx file and related connection string in app.config
and add Edmx item with same name as previous again.
this worked for me.

Changing Lightswitch database connection at run time

I am looking to make it possible for my application to change it's connection string at runtime. I have a connection string in the Web.Config file, but when I update the config file and restart the application, the connection string does not update. Also, I do not seem to be able to use the configuration manager from within my application. Is changing the connection string in the Web.Config file the best way to go about making this a dynamic connection?
<add name="486f1ab5-d3c4-4fc5-805b-0afbcf0fa46b" connectionString="Data Source=.\MyServer;Initial Catalog=Mydatabase;Integrated Security=True" />
Here is a blog post that goes over what you need to do:
LightSwitch Dynamic Connection Strings Now Supported

ProviderName for Sql Server .SDF file to use in app.config

I've created a DB file in a project Add -> New Item -> Local Database and created a table for it.
Now I would like to create a connection string for it in app.config.
The problem is that all example code that I find uses code only to create a connection, and not app.config. Hence I can't figure out which providerName I should use.
So what is it?
<add name="DemoDb" providerName="XXXXXX" connectionString="Data Source=ExampleDb.sdf;Persist Security Info=False;"/>
System.Data.SqlServerCE.4.0 or System.Data.SqlServerCe.3.5 depending framework version

Unable to read connection string from Config File

I have an app.config file in my project as shown below.
I have following code to read the connection string:
string connectionstring = ConfigurationManager.ConnectionStrings["LibraryReservationSystemEntities"].ConnectionString;
It is showing exception as listed below.
Object reference not set to an instance of an object.
How can we correct it?
Note: This is a class library project. I copied this connection string from another project which is having EMDX file for EF. I have only one project in my current solution.
Note: I need to instantiate a ObjectContext (of EF) from a my project. The EMDX is available in a different project.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="LibraryReservationSystemEntities" connectionString="metadata=res://*/MyEDMtest.csdl|res://*/MyEDMtest.ssdl|res://*/MyEDMtest.msl;provider=System.Data.SqlClient;provider connection string="Data Source=.;AttachDbFilename=C:\DevTEST\Databases\LibraryReservationSystem.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
REFERENCE
How do I programmatically set the connection string for Entity-Framework Code-First?
Best way to initialize an entity framework context?
You can't have a config file for a library project. This configuration file is related to the executed assembly, which could be a winform app, WPF app, console app, ASP.Net website in IIS...
Add your ConnectionStrings section in the app.config (or web.config) file of the actual assembly that is executed.
Check this
you need to add a .dll reference for configuration manager
recheck if your connection string is right
check if you have more than one configuration file ex. web.config and app.config; so the ConfigurationManager is referencing the wrong file in the solution.
If ConnectionStrings["myConnection"] returns null, then dereferencing it to get the Name property will fail in the constructor. Is that definitely not where the bug is?
Why not put a breakpoint on that line and take a look in ConfigurationManager.ConnectionStrings to check what it thinks it's got - and check very carefully for typos.
After that, put a breakpoint on the first line of the method, and check what the value of connectionString is. Passing in null to the SqlConnection constructor doesn't actually throw an exception, but you'd get an InvalidOperationException when you try to open it.

WebService doesn't read web.config

I've got 3 connectionstrings in web.config, and I used theirs like this:
using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SomeName"].ConnectionString))
Every metgod is called by winforms application.
One of webmethods doesn't work properly because it reads only one connectionString:
data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true
It's not a connectionString from my web.config .
I invoke every method in the same way.
How it's impossible ??
EDITED:
I use facade: This is structure:
WinForms calls WebMethod SaveItem
SaveItem calls method on Facade: SaveItemAndDoDatabaseStuff
SaveItemAndDoDatabaseStuff does database stuff.
We can't see your web structure, but is it possible that your app isn't configured as an application in IIS, therefore is picking up the master web.config? Which would look exactly like that...
Go into IIS and ensure it is an application (it may have a cog icon).
If your WinForms application talks directly to database X (not via the web service), then the connection string for database X should be in app.config (in the WinForms project).
If your Web Service (as I understand, this includes your facade and your database layer), talks to databases X, Y and Z, then the connection strings for X, Y, and Z need to be in web.config (in the Web Services Project).
It's using the default connection string asp.net has (in the machine.config in the .net installation folders).
Do a clear:
<configuration>
<connectionStrings>
<clear/>
... your connection strings here
</connectionStrings>
</configuration>
Btw, when you say you are using "SomeName" in the connection string. It isn't surely any random connection string you used, its the default: "LocalSqlServer".
You should store the connection-strings in the web.config or app.config in whatever project that you are executing.
In your case, you should have the connection-strings in your app.config for your winforms application.
Why not just add a Trace line to print out the configuration file being used just before you ask for the connection string. Simply add the following line:
System.Diagnostics.Trace.WriteLine(
System.AppDomain.CurrentDomain.SetupInformation.ConfigurationFile,
"APP_CONFIG");
Set a breakpoint after this and look at the Output window for a line that starts with "APP_CONFIG:". This will give the full path to the configuration file and allow you to determine where it's being loaded. If you still see a discrepancy between the runtime values and the configuration file then likely something is changing those values at runtime within your application.
This is a late answer, but perhaps worthwhile.
I have a web-service project, and I want to run it in two modes.
One is "local as app" (for testing), and for that, at least in my current system setup, the file where it reads from is
Web.config (which it apparently reads in deug mode INSTEAD of Web.Debug.config, at least for database configuration)
So, one replace the attribute section with and copy in the ones you would use in the "Calling project for hte web service).
So replace
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=ReleaseSQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
with
<appSettings>
<!-- Database Connection -->
<add key="AppDatabase" value="RedactedDatabase"/>
<add key="AppLoginID" value="RedactedLoginID"/>
<add key="AppLoginPwd" value="RedactedPwd"/>
</appSettings>
The above are found in app.config in the "calling project".... To me, this is more elegant anyway.
Now it will work in both modes.
One could use a conditional compile in the C#, but now you just read it in:
C# code:
String whichDatabase = System.Configuration.ConfigurationManager.AppSettings["AppDatabase"];
String appUsedID = System.Configuration.ConfigurationManager.AppSettings["AppLoginID"];
String appUsedPwd = System.Configuration.ConfigurationManager.AppSettings["AppLoginPwd"];
The above works in either mode, without conditional compile directives.

Categories

Resources