Mefhisto1 Mefhisto1 - 3 months ago 22
C# Question

Entity framework throwing invalid operation exception - Connection string in app.config not found

I added a new ADO.NET data model from the database, and everything generated fine.

Then I try to make a call to get one of the tables:

public Sensor[] GetAllRegisteredSensors()
{
using (var context = new ClientSensorLocationEntities())
{
try
{
return context.Sensors.ToArray();

}
catch (Exception ex)
{
throw;
}
}
}


and I get an exception:


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


Pretty self-explanatory and then I went to my
app.config
file which looks like this:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="ClientSensorLocationEntities" connectionString="metadata=res://*/ClientSensorLocationModel.csdl|res://*/ClientSensorLocationModel.ssdl|res://*/ClientSensorLocationModel.msl;
provider=System.Data.SqlClient;provider connection string=&quot;data source=MYUSER\SQLEXPRESS;initial catalog=ClientSensorLocation;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;"
providerName="System.Data.EntityClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
</configuration>


So the connection string with that name exists. What seems to be the problem then?

Answer

If you are using DbContext from referencing Projects, you also need to register the connection string on the project configuration file.

For example, if you are using the DbContext on a web project, check if the connection string is on the web.config.

Comments