Background
Code first: After modifying the model, to make it persistent to the database, you always need to delete the original database and create it again (dropcreatedatabaseifmodelchanges). In this case, a problem occurs, when our old database contains some test data, all the original data will be lost after the persistent update, so we can introduce the data migration function of EF to complete the process.
Requirements
- Nuget installed
Process example
// Original Model
using System.Collections;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;public class Lesson { public int lessonID { get; set; } [Required] [MaxLength(50)] public string lessonName { get; set; } [Required] public string teacherName { get; set; } public virtual UserInfo UserInfo{get;set;}}
// New Model
using System.Collections;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;public class Lesson { public int lessonID { get; set; } [Required] [MaxLength(50)] public string lessonName { get; set; } [Required] [MaxLength(10)] public string teacherName { get; set; } public virtual UserInfo UserInfo{get;set;}}
Note: The difference is that we have added a length limit to the teachername attribute.
Next, we will start to persist this model to the database (now we only modify the attribute. In this case, the length of this field in the database is nvarchar (max), not nvarchar (10 ))
1: configure the database connection in config:
<connectionStrings> <add name="TestUsersDB" connectionString="Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=TestUsersDB;Data Source=XCL-PC\SQLEXPRESS" providerName="System.Data.SqlClient" /> </connectionStrings>
2: Open the nuget console:
3: run the Enable-migrations command.
The following error may occur:
Checking if the context targets an existing database...
Detected database created with a database initializer. scaffolded migration '2017 _ initialcreate 'corresponding to existing database. to use an automatic migration instead, delete the migrations folder and re-run enable-migrations specifying the-enableautomaticmigrations
Parameter.
Code first migrations enabled for project mvcapplication1.
The following folder appears in the project:
Open configuation. CS and make the following changes:
public Configuration() { AutomaticMigrationsEnabled = true; }
Execute Update-database again:
Because I changed the length from Max to 10, when updating the data structure, it thinks this operation will cause data loss, as shown below:
Specify the '-verbose' flag to view the SQL statements being applied to the target database.
No pending code-based migrations.
Applying automatic migration: 201212090848057_automaticmigration.
Automatic migration was not applied because it wowould result in data loss.
If it's okay, just add a mandatory parameter to the command:
Enable-migrations-Force
Last run again: Update-Database
The original data in the database is not lost!
3: