EF architecture ~ CodeFirst data migration and database deletion prevention, efcodefirst
Back to directory
This article introduces two concepts to Prevent Automatic database deletion. This is because the original database is deleted when the data entity changes in code first mode,And add new data tables, but this is unacceptable for our operating environment database,The second problem is data migration. When a new entity is created, how to respond to the database becomes a problem. Of course, the implementation is also very simple.MigrationsTool.
1. Database deletion prevention
Change the base class of your business DbInitializer to CreateDatabaseIfNotExists to solve this problem. This is what needs to be done during data initialization. Generally, we will choose to automatically update the database when the entity changes, however, this method has a big impact, so we do not advocate it.
Public class ManagerInitializer:CreateDatabaseIfNotExists <ManagerContext>{Protected override void Seed (ManagerContext context)
{// Initialization code }}
2. Data Migration
This problem must also be solved. After adding an object, the database does not have a corresponding table, so we need to useMigrationsCommand to update the database, the specific operation is as follows
1. EnableMigrationsFunction
enable-migrations -force
2. update the database
update-database
3. After the program runs successfully,
Now you can view your own database. The newly added entities are automatically added to the database.
It is worth noting that the original data of the database will not be lost during database migration through this method,Even if you add fields to the original table, old data will not be lost, and new fields will have default values.
For EF7, it only supports the Code First mode, so this mode will become the mainstream in the dotnet framework!
Back to directory