I've deleted the connection string from my web.config and Entity Framework is still connecting to the database! Where is the connection string being set? This is an issue because I need to make the live version of my website point to the live database.
Right click on your Entity Framework mode (edmx file) > goto Properties. You'll see the connection string there. If your Entity Model is in a separate project, then it must be in it's own settings file.
Right-click on your connection and select "Properties". You will get the Properties window for your connection. Find the "Connection String" property and select the "connection string". So now your connection string is in your hands; you can use it anywhere you want.
In ASP.NET Core the configuration system is very flexible, and the connection string could be stored in appsettings. json , an environment variable, the user secret store, or another configuration source.
Here's a gotcha I found with the "convention over configuration" philosophy when it comes to trying to connect to existing databases (like you're doing).
If your DbContext class (e.g. Northwind) is in a namespace (e.g. MvcProject), for some reason EF won't match the name of the class with a connection string in web.config named "Northwind" (or "MvcProject.Northwind"), and then it will just create a connection string defaulting to the local SQLEXPRESS instance, with a database called "MvcProject.Northwind". This will be an empty database. And you'll break your head trying to figure out why you're getting no data back, until you realize that you're not connected to the right DB.
The way I got around this (not elegant but it's the quickest way I found to fix it): add a constructor to your DbContext class that calls the base with the name of the connection string in web.config - e.g.
namespace MvcProject
{
public class Northwind : DbContext
{
public Northwind() : base("Northwind") {}
}
}
Hope that helps someone out there ;-)
You'll need something like this:
<configuration>
<connectionStrings>
<add name="MyContext"
connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=YourDatabaseName"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Or if your database resides is App_Data
folder:
<configuration>
<connectionStrings>
<add name="MyContext"
connectionString="Data Source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|YourDatabaseFilename.mdf;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Replace MyContext
with name of your class that extends DbContext
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With