Using EF Code First, I know that I have to match my DbContext class name with the database’s connection string name attribute to make them work together. But the following code does not work:
public class UserDbContext : DbContext
{
public DbSet<Users> Users { get; set; }
}
along with this connection string:
<add name="UserDbContext"
connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\Users.mdf;
Integrated Security=True"
providerName="System.Data.SqlClient" />
But instead I end up having to use this connection string instead, which points directly to the model along with the DbContext name
<add name="NextFlicksMVC4.Models.userAccount.Users+UserDbContext"
connectionString="Data Source=(LocalDB)\v11.0;
AttachDbFilename=|DataDirectory|\Users.mdf;
Integrated Security=True"
providerName="System.Data.SqlClient" />
It works as intended, I connect to a LocalDB in the App_Data Folder.
Can anyone explain to me why it only works when I point it to the full path of the DbContext class?
The default constructor, from the documentation:
From the remarks section for DbContext:
If you use a decompiler to look at the code for the default constructor in
DbContext, you’ll see it callsGetType().ToString()on theDbContextinstance and uses that value to find the connection string. So it makes complete sense why the fully-qualified type name of yourDbContextis a valid convention to use for naming your connection string.In your example,
UserDbContextis not the proper name because it is a nested class. You can leave off the namespace but at a minimum you will have to name your connection stringUsers+UserDbContext. If you want to have the connection string match the class name alone, you can’t nest it inside your model.