EF Code First Data Migration Learning note

Source: Internet
Author: User
Tags connectionstrings

Preparatory work

1. Create a new console project, perform install-package entityframework//Install EF Environment in "Package Management Console"

2. Create a new Class (Paper) under the project, which is code in code first. Once built, Ctrl+shift+b builds the project. (if not generated, the controller can not find the type or other error)

3. Add the node connectionstrings under the configuration of App. Config or Web. config:

< connectionStrings >  <  name= "DefaultConnection"  connectionString= "Data source=.;i Nitial Catalog=mysite; Persist Security info=true; User id=a; Password=b "  providerName=" System.Data.SqlClient "/></ connectionStrings >

4. The new class Sitedbcontext under the project as the data context for the project:

 Public class sitedbcontext:dbcontext{    publicbase("defaultconnection"  {}    publicgetset;}}

Define the constructor under the class, passing the name of the connectionstring of step 3 to the base class constructor. In this way, data acquisition is linked through the database in step 3. Also define the properties of the Dbset type of the class that is already defined in the data context. Prepare for the subsequent migration.

Additional table

1. At this point, if you call Sitedbcontext directly in the program's main function and then manipulate the papers data below, the papers table is automatically generated in the database. Debug the program.

2. Open migration: Enable-migrations

If'201502150256371_initialcreate' corresponding to existing database. To use an automatic migration instead, delete the Migrations folder and re-run enable-migrations specifying the-   for Project Migrationtest.

After executing the command, the folder migrations is automatically generated in the project, and the Configuration.cs and 201502150256371_initialcreate.cs under the folder

Add Property

1. Modify the structure of the class paper, here we add the property public string Test{get;set;}, build the program.

2. In order to verify that the database will not be fully rebuilt, we manually insert several data into the database:

3. Increase the migrated node: Add-migration Papertest (based on the previous operation, the program will automatically determine the changes based on the last migration when executing this command)

After executing the above command, a class is automatically generated under folder migrations:

 Public Partial classpapertest:dbmigration{ Public Override voidUp () {AddColumn ("dbo. Papers","Test", C =c.string ()); }         Public Override voidDown () {Dropcolumn ("dbo. Papers","Test"); }}

The name of the class is defined after the add above. There are two methods under the class, one is up and the other is down. In the up, the changes that need to be upgraded are recorded, and here is the papers table that adds the column test. As soon as we execute the update-database in the back, we execute the UP function below this class.

A simple introduction to the down function here is designed to roll back the modifications. If a user wishes to revert to a migration node, the program automatically determines which migrations to roll back, and executes their down function, based on the migration that has been performed.

4. Execute the Update-database and upgrade the changes here to the database.

Review the prompt and enter the parameter-verbose after the update command to see the details of the upgrade.

The second row runs the migrated object 201502260053423_papertest.

Third row, run the seed function. Here is a description of the seed function in Configuration.cs:

protected Override voidSeed (Migrationtest.sitedbcontext context) {//This method is called after migrating to the latest version. //You can use the dbset<t>. AddOrUpdate () Helper extension method//To avoid creating duplicate seed data.    e.g. //    //context. People.addorupdate (//p = p.fullname,//new Person {FullName = "Andrew Peters"},//new Person {FullName = "Brice Lambson"},//new Person {FullName = "Rowan Miller"}//    ); //}

Looking closely at the statement of the note, you can see that this function is called every time you migrate to the latest version. Use the AddOrUpdate function to avoid generating duplicate data. The last side gives an example of a addorupdate invocation.

The usefulness of this function, I temporarily understand, is to generate initialization data. No matter how it is migrated, this data will exist.

5. After performing the above actions, go back to the database to view the data structure and the contents of the content:

In this, the operation to add attributes above the existing class is complete.

Delete attribute

The operation to delete an attribute is similar to the action of adding a property. First modify the class structure, shielding the above//public string Test {get; set;}. Then add a migration node named Delpapertest. Execute this command to generate the appropriate migration class file. Finally execute update-database, where we use the Update-database-verbose command to see the details of the execution:

 pm> update-database-verboseusing StartUp project ' Migrationtest '. Using NuGet project ' Migrationtest '. Specify the '-verbose ' flag to view the SQL statements being applied to the target database. Target database is: ' MySite ' (DataSource:., Provider:System.Data.SqlClient, origin:configuration). Applying explicit migrations: [201502260118534_delpapertest]. Applying explicit migration:201502260118534_delpapertest.declare @var0 nvarchar () SELECT @var0 = Namefrom Sys.default_constraintswhere parent_object_id = object_id (N ' dbo. Papers ') and Col_name (parent_object_id, parent_column_id) = ' Test '; IF @var0 is not NULL EXECUTE (' ALTER TABLE [dbo].[ Papers] DROP CONSTRAINT [' + @var0 + '] ') ALTER TABLE [dbo]. [Papers] DROP COLUMN [Test]insert [dbo]. [__migrationhistory] ([Migrationid], [Contextkey], [Model], [productversion]) VALUES (n ' 201502260118534_delpapertest ', n ' migrationtest.sitedbcontext ', 0x1f8 ... , N ' 6.1.2-31219 ') Running Seed method.  

Looking at the SQL statements in the above, first look for the column test-related constraints, and if so, delete the constraints first. The column is then deleted, and a row of migration records is written in the Migration history table.

Change properties

1. Under the paper class, modify the property name to generate the project:

 Public string Get set; ---Public  stringgetset;

2. In the usual way, next we should add a migrated node. Let's start by looking at the results of this implementation:

Add-migration Modifypaper

Open the automatically generated migration class file 201502260128314_modifypaper.cs:

 Public Partial classmodifypaper:dbmigration{ Public Override voidUp () {AddColumn ("dbo. Papers","DESCAA", C =c.string ()); Dropcolumn ("dbo. Papers","Desc"); }         Public Override voidDown () {AddColumn ("dbo. Papers","Desc", C =c.string ()); Dropcolumn ("dbo. Papers","DESCAA"); }}

As you can see in the up, it does not directly modify the name of the column, but adds the new column DESCAA first, and then deletes the old column desc. There is a consequence of this execution, and if there is data in the column, all data is lost.

3. The results of the implementation of Update-database are as follows:

How can I modify the column names on the basis of preserving existing data?

(in general operation, it is not recommended to modify column names like this, because the database calls may be more than this place, prone to leak change and bug)

Note: Modify the column name as shown in method three below. The following content is obsolete and Liu Wen is only recorded.

1. Directly modify the Class Property desc to DESCAA, and manually modify the database column name to DESCAA. Run the program, will error:

2. Before running the program, delete the Migration folder migrations. Then run the program and report the error above.

3. In the project execute command enable-migrations, regenerate the migration folder. Then run the program, the same error.

4. Delete the project-related migration record in the migration history table in the database, delete the Migrations folder in the project, and then execute enable-migrations, and you will see:

At the same time migrations folder except for Configuration.cs, there is no other class file.

In this case, the property name of the class structure is modified to complete, and the existing data of the database is saved successfully.

But this method, there is a trap.

If after modifying a property, there is an increment property or delete the property, after Add-migration, the auto-generated class, the code will appear:

 Public Partial classdeltestafterchangedescaa:dbmigration{ Public Override voidUp () {createtable ("dbo. Papers", C=New{Paperid= C.int (Nullable:false, Identity:true), Papername=c.string (), DESCAA=c.string (),}) . PrimaryKey (t=T.paperid); }         Public Override voidDown () {droptable ("dbo. Papers"); }}

the above code directly createtable and droptable. This is a failure to execute update-database because the database already has tables papers

At this point, we can choose to manually modify the contents of up and down:

 Public Partial classdeltestafterchangedescaa:dbmigration{ Public Override voidUp () {Dropcolumn ("dbo. Papers","Test"); }     Public Override voidDown () {AddColumn ("dbo. Papers","Test", C =c.string ()); }}

Execute update-database, command complete.

Method Two ( Note: Modify the column name as shown in method three below.) The following content is obsolete and Liu Wen is only recorded. ):

1. On the above basis, modify the DESCAA of the paper class to Desc.

2. Run Add-migration MODIFYDESCAA, get the migrated CS file, manually annotate the up Dropcolumn:

 Public Partial classmodifydesc:dbmigration{ Public Override voidUp () {AddColumn ("dbo. Papers","Desc", C =c.string ()); //dropcolumn ("dbo. Papers "," DESCAA ");    }         Public Override voidDown () {//AddColumn ("dbo. Papers "," DESCAA ", C = c.string ());Dropcolumn ("dbo. Papers","Desc"); }}

3. Execute update-database. In this case, the papers table of the database adds Desc.

4. Enter the database and manually delete the DESC column that you just added, and change the DESCAA column name to Desc.

5. Run the program, you can debug, explain the above modification of the property name Operation succeeded.

6. In order to prevent future migrations to a specific version, a rollback problem occurs. Manually block the code in up and down in step 2 above.

Note here: You cannot manually delete the previous row migration history in the Migration history table, and manually delete the CS file generated by the above 2 steps in the project. This will directly report the above "database context has been changed" error.

The above two methods, after the operation will need to do a certain amount of repair, or the following code first will be a bit of a hidden danger.

The third method of

After debugging the above two methods, it is found that Dbmigration has renamecolumn function.

Hehe, on the basis of this function, it becomes super simple to modify the property name.

1. Change the DESCAA of paper to DESC

2. Execute the add-migration renamedesc command, generate the migration class file, and manually modify the contents of the class file as follows:

 Public Partial classrenamedesc:dbmigration{ Public Override voidUp () {//AddColumn ("dbo.        Papers "," Desc ", C = c.string ()); //dropcolumn ("dbo. Papers "," DESCAA ");Renamecolumn ("dbo. Papers","DESCAA","Desc"); }         Public Override voidDown () {//AddColumn ("dbo.        Papers "," DESCAA ", C = c.string ()); //dropcolumn ("dbo. Papers "," Desc ");Renamecolumn ("dbo. Papers","Desc","DESCAA"); }}

3. Execute the update-database command, the database column name is automatically modified.

It is important to note that when the update command is executed, the program alerts the operation that modifying the column name may cause the SQL scripts of the stored procedure and other calling columns to be invalidated:

This is the actual operation to pay attention to the problem, but also is the author does not recommend random modification of the column name of the main reason-may cause other calls to fail.

Author Small note:

While groping and manipulating, there's a certain understanding of the EF Code First architecture.

1. The migrated association inherits the Dbmigration CS file in the database's Migration history table and under the project's Migrations folder

2. In the Database Migration History table, the field model has some dense migration map, arbitrarily delete the modification will cause "database context is changed" error.

3.Migrations folder under the inherited Dbmigration CS file can be manually modified, here the changes can be very flexible, table and table field additions and deletions, here are.

Understanding the above points and simply using the code first based EF should be fine.

EF Code First Data Migration Learning note

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.