EF applies CodeFirst mode, summary of basic usage points of data migration

The first time I used EntityFramework for CodeFirst development, I encountered many problems when doing data migration. I spent a whole day learning and adjusting, and finally learned the basic usage and key points. Now I have sorted it out and posted it. I hope it can be of help to beginners like me. It is worthwhile to take less detours and spend less time exploring.




[plain] view plain copy

print?


      1. Model Design 
    1.      1. Follow the EF standard, pay attention to the table relationship pairing 

 

           2. Try to write all the necessary attributes and descriptions in the data model 
    1.      3. EF default id field is the primary key, if not, you need to specify the primary key 

 

       
    1. 2. Data Migration 

 

           1. Command running environment: visual studio toolbar->tools->NuGet package manager->package manager console 
    1.      2. Basic commands and common parameters 

 

              > get-help command to get help (eg: get-help Enable-Migrations –detailed) 
    1.            --detailed detailed usage 

 

              > Enable-Migrations to enable migrations 
    1.            -Force force override 

 

                 -ProjectName target project (the project where the migration class is located) 
    1.            -StartUpProjectName start the project (contains the project where the database connection string configuration file is located) 

 

                 -ContextTypeName database (class) to be migrated 
    1.            -ConnectionStringName specifies to use the name of the connection string in the configuration file 

 

                 -ConnectionString specifies the connection string to use 
    1.            -ConnectionProviderName specifies the provider name of the connection string 

 

                 -MigrationsDirectory specifies the directory for migration files (multiple databases, for independent automatic migration) 
    1.         > Add-Migration to add migration scripts for pending Model changes 

 

                 -Force 
    1.            -ProjectName 

 

                 -StartUpProjectName 
    1.            -ConfigurationTypeName specifies the migration configuration to use 

 

                 -IgnoreChanges Ignore the detection of pending model changes and create an initial, empty migration for an existing database enabled migration. 
    1.            -ConnectionStringName   

 

                 -ConnectionString       
    1.            -ConnectionProviderName  

 

              > Update-Database updates pending migrations to the database 
    1.            -Force 

 

                 -ProjectName 
    1.            -StartProjectName 

 

                 -ConfigurationTypeName 
    1.            -ConnectionStringName  

 

                 -ConnectionString  
    1.            -ConnectionProviderName  

 

                 -SourceMigration only works if -Script is on. Specifies the name of the migration to use as the starting point for the update. Omit to use the last migration applied. 
    1.            -TargetMigration Specifies the name of the migration to which the database is updated. 

 

                 -Script Generate SQL script 
    1.         > Get-Migrations to get applied migrations                                    

 

           3. Example of migration operation steps: 
    1.              DataBase : In the solution, the data model layer project name 

 

                   Member : The name of the startup item in the solution 
    1.              DataBase.Member.MemberEntities : The data context to which data migrations need to be applied 

 

               a. To enable migration for the first time, enter the command:  
    1.              Enable-Migrations -ProjectName DataBase -StartUpProjectName Member -ContextTypeName DataBase.Member.MemberEntities  

 

                   and press Enter, then open the Configuration.cs file in the generated Migrations folder,  
    1.              Change AutomaticMigrationsEnabled = false; in the constructor to AutomaticMigrationsEnabled = true; 

 

                   If there are multiple databases, each database needs to specify the migration file independently. The command format is as follows: 
    1.              Enable-Migrations -ProjectName DataBase -StartUpProjectName Member -ContextTypeName DataBase.Member.MemberEntities -MigrationsDirectory:MemberMigrations 

 

               b. When the model is changed, enter the command: add-migration update20150508 -ProjectName DataBase -StartUpProjectName Member -Force and press Enter to create a migration script 
    1.              Then enter the command: Update-Database -Verbose -ProjectName DataBase -StartUpProjectName Member and press Enter to execute the migration operation 

 

           4. Configure automatic migration 
    1.          Register automatic migration in the entry method (function) of the application: 

 

               Database.SetInitializer(new MigrateDatabaseToLatestVersion());  
    1.          Note: Configuration.cs generates an internal sealed class. If it is not in the startup assembly, it needs to be modified to public 

 

           5. To migrate the database version from the visual studio environment, migrate.exe can be used, please refer to: http://msdn.microsoft.com/zh-cn/data/jj618307 
    1.  

 

      3. Matters needing attention: 
    1.      1. The connection string is not as complicated as the one automatically generated by DBFirst, and can be in the following format: 

 

              
    1.      2. When there is a pending Model change, the operation will be abnormal. Pay attention to the operation steps and clean up the pending migration if necessary. 

 

           3. If the data in the revised database needs to be adjusted, use the Seed method in the Configuration.cs file. The example is as follows: 
    1.         protected override void Seed(DataBase.Member.MemberEntities context) 

 

              { 
    1.             var users = new List

 

                  { 
    1.                 new User { Account = "test",   Password = "123" }, 

 

                      new User { Account = "admin",   Password = "456" } 
    1.             }; 

 

                  users.ForEach(s => context.Users.AddOrUpdate(p => p.Account, s)); 
    1.             context.SaveChanges(); 

 

              } 



[img]http://static.blog.csdn.net/images/save_snippets.png" alt="[/img]

[code="plain"]I. Model design
     1. Follow EF standards, pay attention to table relationships Pairing
     2. Try to write all the necessary attributes and descriptions in the data model
     3. The default id field of EF is the primary key, if not, you need to specify the primary key

2. Data migration
     1. Command operating environment: visual studio toolbar->tools- >NuGet Package Manager->Package Manager Console
     2. Basic Commands and Common Parameters
        > get-help Commands to get help (eg: get-help Enable-Migrations –detailed)
           –detailed detailed usage
        >Enable-Migrations Enable migrations
           -Force force coverage
           -ProjectName target project (the project where the migration class is located)
           -StartUpProjectName start the project (including the project where the database connection string configuration file is located)
           -ContextTypeName The database (class) that needs to be migrated
           -ConnectionStringName specifies the name of the connection string used in the configuration file -ConnectionString specifies the connection string to use            -ConnectionProviderName specifies the provider name
           of the connection string -MigrationsDirectory specifies            the directory of the migration file (multiple databases, for independent automatic migration)         > Add- Migration Add migration scripts for pending model changes            -Force            -ProjectName            -StartUpProjectName            -ConfigurationTypeName Specifies the migration configuration to use            -IgnoreChanges Ignore pending model changes detected and create an initial, empty migration for the existing database to enable migrations.            -ConnectionStringName             -ConnectionString                 -ConnectionProviderName         > Update-Database Update pending migrations to database            -Force













           -ProjectName
           -StartProjectName
           -ConfigurationTypeName
           -ConnectionStringName
           -ConnectionString
           -ConnectionProviderName
           -SourceMigration Only valid if -Script is on. Specifies the name of the migration to use as the starting point for the update. Omit to use the last migration applied.
           -TargetMigration Specifies the name of the migration to which the database is updated.
           -Script Generate SQL script
        > Get-Migrations Get the migrations that have been applied                                  
     3. Examples of migration operation steps:
             DataBase: In the solution, the name of the data model layer project
             Member: In the solution, the name of the startup item
             DataBase.Member.MemberEntities: Required The data context to which data migrations are applied
         a. To enable migration for the first time, enter the command:
             Enable-Migrations -ProjectName DataBase -StartUpProjectName Member -ContextTypeName DataBase.Member.MemberEntities
             and press Enter, then open the Configuration.cs file in the generated Migrations folder,
             put the constructor In AutomaticMigrationsEnabled = false; change to AutomaticMigrationsEnabled = true;
             if there are multiple databases, each library needs to specify the migration file independently, the command format is as follows:
             Enable-Migrations -ProjectName DataBase -StartUpProjectName Member -ContextTypeName DataBase.Member.MemberEntities -MigrationsDirectory: MemberMigrations
         b. When the model is changed, enter the command: add-migration update20150508 -ProjectName DataBase -StartUpProjectName Member -Force and hit enter, create a migration script
             and enter the command: Update-Database -Verbose -ProjectName DataBase -StartUpProjectName Member and hit back car key to perform the migration operation
     4. Configure automatic migration
         Register automatic migration in the entry method (function) of the application:
         Database.SetInitializer(new MigrateDatabaseToLatestVersion());
         Note: Configuration.cs generates an internal sealed class. If it is not in the startup assembly, you need to Modify it to public
     5. To migrate the database version from the visual studio environment, migrate.exe can be used, please refer to: http://msdn.microsoft.com/zh-cn/data/jj618307

3. Notes:
     1. The connection string is not required It is so complicated that DBFirst automatically generates the following format:
        
     2. When there is a pending Model change, the operation will be abnormal. Pay attention to the operation steps and clean up the pending migration if necessary.
     3. If the data in the revised database needs to be adjusted, use the Seed method in the Configuration.cs file. The example is as follows:
        protected override void Seed(DataBase.Member.MemberEntities context)
        {
            var users = new List
            {
                new User { Account = "test", Password = "123" },
                new User { Account = "admin",   Password = "456" }
            };
            users.ForEach(s => context.Users.AddOrUpdate(p => p.Account, s));
            context.SaveChanges();
        }

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326568527&siteId=291194637