mvc connection string code first

2019-07-31 15:09发布

问题:

im new to mvc and im trying out some stuff with code first. im currently having problems with my dbase, whenever i build my application the build finishes successfully but i dont see my dbase get created whenever i check my local server. was wondering if there's something im missing on my connection string.

<connectionStrings>
 <add name="mydbase" connectionString="Data Source=localhost;Database=mydbase;Trusted_Connection=yes;" providerName="System.Data.SqlClient" />
</connectionStrings>

or maybe i should be looking at the global file? i just added an initializer there for the seed and nothing more, i dont see any reason why that would mess that up...

thanks in advance!

回答1:

The database isnt committed until you've used the Context to which it relates.

For example, in a test project, I called my initializer

 Database.SetInitializer<TestContext>(new TestContextInitializer());

and then used the context for some task i.e.

_testContext = new TestContext();
var stuff = from te in _testContext.TestTable select te;

It's at this point the db is created.



回答2:

Normally the database gets created when you run the application, not when you build it. You may take a look at the following blog post about the different database initialization options (AlwaysRecreateDatabase, CreateDatabaseOnlyIfNotExists, RecreateDatabaseIfModelChanges).