问题
I'm using Code First with Entity Framework 5 using MVC4 and MVC Scaffolding (link/tutorial: http://www.codeproject.com/Articles/468777/Code-First-with-Entity-Framework-5-using-MVC4-and?msg=4531106#xx4531106xx) to create my database from my models. So, basically, when I run the app, the app drops and creates a new database if my model changes. That's great. Now, obviously, this is great for local development.
But what about when my app goes to production? How do I tell the code to NOT do this anymore, and rather point my app to use the database I have hosted on GoDaddy? I changed the connection string in the web.config to point to that of the GoDaddy database, but this isn't working. What happens is the code still tries to use the old connection string for some reason unknown to me. I can't seem to get my app to NOW use the database I created on GoDaddy. I'm starting to regret going down the code-first route....
Here's the line of code in my Application_Start
method that auto-generates my database (in this case, only if my model changes):
System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<CapWorx.QuikCap.Models.CapWorxQuikCapContext>());
回答1:
(as per our discussion / comments)
simple rule is -
If you have the 'non-static ctor' CapWorxQuikCapContext() : base("connection") - then you have to use that same name in the config as well.
Otherwise - you have to name the connection string the same as your Context class - i.e. exactly the CapWorxQuikCapContext.
If you don't - EF/CF makes its own 'connection' path - i.e. making some default db name - like your context - or like you have in the ctor
回答2:
I found the solution to my problem.
Originally, I had the following in my context's constructor:
static CapWorxQuikCapContext()
{
Database.SetInitializer(new CodeFirstSeeder.Xml.DropCreateDatabaseAlways<CapWorxQuikCapContext>());
}
Note that the CodeFirstSeeder is irrelevant at this point- it's just a strategy I installed to seed some sample data. Anyways, I changed the above to be:
public CapWorxQuikCapContext()
: base("DefaultConnection")
{
}
This tells my app to look at the connection string called "DefaultConnection" and use it for its data source.
来源:https://stackoverflow.com/questions/15767739/entity-framework-code-first-how-do-i-tell-my-app-to-now-use-the-production-dat