简体   繁体   中英

How does EF Code First create connection string first time?

Given: An MVC (Code First DB) project that needs the first time "default" connection string regenerated.

Reason I had some errors and in attempt to fix needed to uninstall SQL servers and reinstall. Now project won't connect to anything. Web Config still shows old string like this:

 <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-TestReporting-20150127073048.mdf;Initial Catalog=aspnet-TestReporting-20150127073048;Integrated Security=True" providerName="System.Data.SqlClient" />

Since reloading SQL2012 Express and ensuring LocalDB was checked at install time, no connection is made, no DB Generated from a previously working project.

As it turns out the connection string in my case was failing because there was an AttachFile name attribute value in the connection string, where the MDF file did not exist! Chicken and Egg type issue....

Step 1) To get Code First to regenerate the MDF file, simply rename the DBContext class name to something new. Not optimal but good luck finding any other way.

Step 2) I also removed the AttachFile configuration in connection string just to see how this all works, lo... the attach stuff wasn't even needed!

  <add name="DefaultConnection" 
    connectionString="Data Source=(LocalDb)\v11.0; 
    Initial Catalog=TestReporting; 
    Integrated Security=True" 
    providerName="System.Data.SqlClient" /> 

In the end, there seems to be a bug in MDF generation. Code First should at least look for the file and then decide what to do because any Migrations work doesn't work, CreateIfNotExists didn't work, reinstalling SQL 2012 didn't work and even "Repairing" VS2013 didn't work...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM