Back to Catalog
This article introduces two concepts, anti-database automatic deletion, because in code first mode, when the data entity changes, the original database is deleted, and the new data table is added, but this is not acceptable to our operating environment database, The second problem is the data migration problem, when you have a new entity established, how to respond to the database, this becomes a problem, of course, the implementation is also very simple, we directly use the Migrations tool.
An anti-database delete
Change the base class of your business Dbinitializer to createdatabaseifnotexists to solve this problem, this is what you need to do when the data is initialized, and generally, we will choose to update the database automatically when the entity changes, but this has a big impact. Therefore, we do not advocate the use of.
Public class createdatabaseifnotexists<managercontext> { protectedoverridevoid Seed (managercontext context)
{ // Initialize code } }
Two data migrations
This problem is also necessary to solve, our entity added, the database does not have a corresponding table, we need to use the Migrations command to update the database, the operation is as follows
1 Turn on migrations function
Enable-migrations-force
2 Updating the database
Update-database
3 after the program runs successfully,
At this point you look at your own database, the new addition of the entity has been automatically added to the database, hehe.
It is important to note that this method of database migration, the database of the original data is not lost, even if you add fields on the original table, the old data will not be lost, the new field will have a default value.
For EF7, it only supports code first mode, so this mode will become mainstream in the dotnet framework!
Back to Catalog
EF schema ~codefirst Data migration and anti-database removal