Reputation: 22652
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
Upvotes: 0
Views: 3516
Reputation: 2971
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.
Upvotes: 0
Reputation: 48975
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.
Upvotes: 1
Reputation: 2971
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.
Upvotes: 0