[Migration]-detailed explanation of Entity Framework instances

Source: Internet
Author: User
1. Entity Framework migration command (get-help entityframework)

Enable-migrationsEnable migration

Add-migrationAdd a migration script for pending model changes

Update-DatabaseUpdate suspended migration to the database

Get-migrationsObtain the migration of an application

Ii. Custom migration

An existing demo has the following product model:

   1:  public class Product
   2:  {
   3:   
   4:  public int ProductId { get; set; }
   5:   
   6:  public string ProductName { get; set; }
   7:   
   8:  public decimal Price { get; set; }
   9:   
  10:  }

Modify the product and add the following two attributes:

   1:  public DateTime CreateDate { get; set; }
   2:   
   3:  public string Unit { get; set; }

Both createdate and unit are required.

1. Enable-migrations

RunEnable-migrationsStart migration.

RunGet-help enable-migrations-detailedView the detailed usage of enable-migrations.

-Contexttypename: Specifies the context to be used.

-Enableautomaticmigrations

-Projectname: Specifies the project to which the created Migration class is added.

-Startupprojectname: The project where the configuration file to be used is located

-Connectionstringname: Specifies the name of the connection string in the configuration file.

-Connectionstring: the connection string used.

-Connectionprovidername: Specify the provider name of the connection string.

-Force rewrite migration Configuration

Run in this demo

Enable-Migrations -ProjectName Demo.Domain -StartUpProjectName MigrationsDemo

The execution result is: it is detected that the database is created by the database initializer and the initialization migration script is set up for the existing database. In this demo, A migrations folder is created in the demo. Domain project, and two files in migrations: configuration. CS and 201311010641361_initialcreate.cs

Configuration class. This class allows you to configure the migration behavior for the context.

Initialcreate migration. This migration is generated before migration is enabled, because we asked code first to automatically create a database in advance. The code in this base frame migration indicates the objects already created in the database.

If no database has been created, this initialcreate migration will not be added to the project. Instead, when you call add-migration for the first time, the code used to create these tables will create a base frame for the new migration.

2. Add-migration

RunAdd-migrationBuild a pending model change migration script.

RunGet-help add-migration-detailedView the detailed usage of add-migration.

-Name: Specifies the name of the custom script.

-Force

-Projectname

-Startupprojectname

-Configurationtypename: Migration configuration used

-Ignorechanges ignores detected pending model changes and creates an empty migration. This option can be used to create an initial, empty migration for an existing database to enable migration.

-Connectionstringname: Specifies the name of the connection string in the configuration file.

-Connectionstring: the connection string used.

-Connectionprovidername: Specify the provider name of the connection string.

Run in this demo

Add-Migration Add_Product_CreateDateAndUnit -ProjectName Demo.Domain

Generated add_product_createdateandunit:

 

2.1 SQL Method

As mentioned above, both createdate and unit are required. For example, unit is of the string type. The default value updated to the database is null. The default value of createdate is 0:00:00, as shown in figure

To change the value of createdate or unit, you can use the SQL method in up:

Note: when updating the script, set unit to Chinese. Remember to add 'n'. Otherwise, the updated content in localdb will change '? ', Not in SQL Server 2008 R2. It is a good habit to add any database!

2.2 Use of ignorechanges

To map existing databases, run add-migration initial and update-database.

In this way, an initial migration is created. On this basis, modify the demo and migrate it.

3. Update-Database

Execute Update-database on the Package Manager Console to update the pending migration to the database.

Run get-help update-database-detailed to view the detailed usage of add-migration.

-SourcemigrationIt is valid only when-script is enabled. Specify the migration name as the Update start point. If this parameter is ignored, the last application migration is used.

-Targetmigration: Specifies the name of the migration to which the database is updated.

-Script: generate an SQL script

-Force

-Projectname

-Startprojectname

-Configurationtypename

-Connectionstringname: Specifies the name of the connection string in the configuration file.

-Connectionstring: the connection string used.

-Connectionprovidername: Specify the provider name of the connection string.

Run in this demo

Update-Database -ProjectName Demo.Domain

3.1 migration to a specific version

As mentioned above, you can use the-targetmigration switch to migrate the database to a specific State. For example, revoke the createdate and Unit fields added to the database. Run

Update-Database -ProjectName Demo.Domain -TargetMigration:InitialCreate

To roll back to an empty database, run the update-database-targetmigration: 0 or-targetmigration: $ initialdatabase command.

3.2 generate an SQL script

To generate an SQL script, use the-script switch. The other two important switches are-sourcemigration and-targetmigration.

For example, to generate an SQL migration script from initialcreate to add_product_createdateandunit, run the following command:

Update-Database -ProjectName Demo.Domain -Script -SourceMigration:InitialCreate -TargetMigration:Add_Product_CreateDateAndUnit

Generate the following SQL script

If the-sourcemigration switch is ignored, the last application migration is used as the start point. If the-targetmigration is ignored, the latest migration is used as the end point.

4. Automatic Upgrade upon application startup

You can register the migratedatabasetolatestversion database initialization item to implement this function. The database initialization item only contains a logic used to ensure that the database is installed correctly. This logic runs when the context is used in the application process (appdomain) for the first time.

Run in demo

Database.SetInitializer(new MigrateDatabaseToLatestVersion<OrderContext, Configuration>());

Configuration generates internal sealed class, which must be changed to public in different datasets.

Use migrate.exe for migration in the Third Region

Copy the command line tool migrate.exe to the Assembly location that contains the migration configuration. You can perform the migration operation outside.

When nuget is used to install the fuse framework, migrate.exe is located in the tools folder of the downloaded package. In the <project folder> \ packages \ entityframework. <version> \ tools

With migrate.exe, You need to copy it to the Assembly location that contains the migration.

If the application targets. Net 4 instead of 4.5, you also need to copy redirect. config to this location and rename it to migrate.exe. config. In this example, migrate.exe enables the correct binding redirection to locate the object framework assembly.

Note: migrate.exe currently does not support x64 assembly.

Use of migrate.exe

Migrate.exe /? Show Help Information

Migrate Assembly [configurationtype] [/targetmigration]

[/Startupdirectory] [/startupconfigurationfile]

[/Startupdatadirectory] [/connectionstringname]

[/Connectionstring] [/connectionprovidername] [/force] [/verbose]

[/?]

Assembly specifies the Assembly that contains the migration configuration type

[Configurationtype] specifies the migration configuration type name

[Connectionprovidername] provider of the specified connection character

[Connectionstring] specifies the connection string used

[Connectionstringname] specifies the name of the connection string used in the configuration file

[Force] indicates that automatic migration is allowed, causing data loss.

[Startupconfigurationfile] specifies the Web. config or app. config of the program.

[Startupdatadirectory] specifies the directory used when parsing a connection string containing | datadirectory |

[Targetmigration] specifies the version to be migrated

[Verbose] specifies the SQL statement and other information output to the console.

Run in this demo

migrate Demo.Domain.dll /startUpConfigurationFile="MigrationsDemo.exe.config" /targetMigration=” Add_Product_CreateDateAndUnit” /verbose
Iv. References

Code first migration

Automated code first migration

Migrate.exe

V. Demo

[Migration]-detailed explanation of Entity Framework instances

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.