sec_goat
sec_goat

Reputation: 1272

Using C# MVC4 and Matching DbContext Class name with ConnectionString name to use the right database?

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?

Upvotes: 2

Views: 3843

Answers (2)

DotNetGeek
DotNetGeek

Reputation: 165

Specify a constructor in UserDbContext class like this and will solve the issue

        public UserDbContext() : base("UserDbContext") {}

Upvotes: 4

Kevin Babcock
Kevin Babcock

Reputation: 10247

The default constructor, from the documentation:

Constructs a new context instance using conventions to create the name of the database to which a connection will be made. By convention the name is the full name (namespace + class name) of the derived context class. For more information on how this is used to create a connection, see the remarks section for DbContext.

From the remarks section for DbContext:

If the parameterless DbContext constructor is called from a derived context, then the name of the derived context is used to find a connection string in the app.config or web.config file.

If you use a decompiler to look at the code for the default constructor in DbContext, you'll see it calls GetType().ToString() on the DbContext instance and uses that value to find the connection string. So it makes complete sense why the fully-qualified type name of your DbContext is a valid convention to use for naming your connection string.

In your example, UserDbContext is 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 string Users+UserDbContext. If you want to have the connection string match the class name alone, you can't nest it inside your model.

Upvotes: 2

Related Questions