Code first: is the database created only after the execution of certain code?

I want to create a database using code first. And my database is always in "DropCreateDatabaseAlways" mode.

I notice that if I am not trying to execute any database query, for example

using (var db = new Models.TnHContext()) { var query = from u in db.Users select u; foreach (var u in query) { txt += u.UserID + "<br/>"; } } 

the database will not be created. If I did not complete it, only I can see the created database. I wonder if this is due to the EntityFramework construct / default behavior?

+4
source share
2 answers

the database initializer is called when the query is executed by context, the ObjectContext is retrieved from the DbContext or the Database.Initialize method is called.

Therefore, if you want to immediately create a database without executing a query, you should use:

 context.Database.Initialize(false); 
0
source

Database initialization is triggered by Entity Framework Ribbons. This will only happen when EF tries to connect to the database. You can manually initiate database initialization using the following.

 using (var db = new Models.TnHContext()) { db.Database.Initialize(force: false); } 

Setting force to false indicates that EF does not start initialization if it has already been started.

0
source

Source: https://habr.com/ru/post/1488134/


All Articles