Code first migrations update database structure (data migration)

Source: Internet
Author: User
Tags connectionstrings
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

  1. 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:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.