The code for 1.DBContext is as follows:
1 Public classContext:dbcontext2 {3 PublicContext ()4:Base("Name=connstr")5 {6 7 }8 9 PublicDbset<menu> Menus {Get;Set; }Ten}
The 2.Menu classes are as follows:
1[Table ("Menu")]2 Public classMenu3 {4 [Key,databasegenerated (databasegeneratedoption.identity)]5 Public intID {Get;Set; }6 [Required]7 Public intPID {Get;Set; }8 [Required]9 Public stringName {Get;Set; }Ten [Required] One Public stringURL {Get;Set; } A}
Ctrl+f5 operation is not a problem.
3. Change the menu class to the following:
[Table ("Menu")] Public classMenu {[key,databasegenerated (databasegeneratedoption.identity)] Public intID {Get;Set; } [Required] Public intPID {Get;Set; } [Required] Public stringName {Get;Set; } [Required] Public stringURL {Get;Set; } Public stringTest {Get;Set; } }
Run again and find this times wrong
The reason for the error is that because the structure of the database has changed, there are two ways to solve the problem.
1. Set to delete the original database after each database structure change and rebuild
You only need to add the following code:
Public Context () Base ("name=connstr") { Database.setinitializer (new dropcreatedatabaseifmodelchanges<context>()); this. Database.initialize (true); }
This is set to run again after the problem, but because the database was deleted and then rebuilt, so the original data are not. To preserve the original data, you can use the migration data migration method
2. Data migration
1) Click on the Tools tab and select Package Management Console
2) Enter the command enable-migrations, and a new migrations folder will be created under the project, including a Configuration.cs file
3) Enter the command add-migration XXXX, this time will be under the Migrations folder to create a new Yyyymmddhhmmss_xxxx.cs file, which includes a down and up method, the table represents the method of data migration rollback and upgrade
4) Enter command update-database-verbose, data migration is complete, you can see the SQL statement of Data migration.
Codefirst Data Migration