EF6 CodeFirst代碼遷移筆記


    由於EF7只支持codefirst only。朕無奈被微軟逼上了梁山學一下codefirst,就算是為明年做准備吧。寫的這些網上大致都有,基本沒啥 新內容,

遷移

使用自動遷移
Enable-Migrations –EnableAutomaticMigrations 
 
第一次遷移
Enable-Migrations
 
 
修改表結構
  • Add-Migration 將基於您已經對模型所做的更改構建下一次遷移的框架。
  • Update-Database 將所有掛起的更改應用到數據庫。
除非確有需要,否則我們要避免使用 Add-Migration,而且我們的重點是讓 Code First 遷移自動計算和應用更改。讓我們使用  Update-Database 來進行 Code First 遷移,並將更改推送到模型,直至數據庫。
  Update-Database –Verbose 
 
 
其實 Add-Migration對我來說就是在Migrations里面生成一個遷移類,這個類標記了對於上一個代碼版本的模型更改。
 Update-Database 成功的話會在數據庫生成一個表或在這個表里面添加一個新的數據。[MigrationId]就是Add-Migration后面我們自定義的名稱。[ContextKey]應該是Configuration的完全限定命名。[Model]是模型的元數據。[ProductVersion]代表使用的EF版本
 
 
 
 

刪除數據庫

如果要一直回滾到空數據庫,可以使用  Update-Database –TargetMigration: $InitialDatabase 命令。
 

回溯數據庫

Update-Database –TargetMigration: TargetMigrationName(遷移命名)
但是回溯到舊數據庫的話可能會有一個問題。我舊的遷移生成某一個表,但是這個表對應的實體類現在已經被我刪了,那怎么辦呢?
 

命令異常:

  Update-Database –Verbose 出現
無法將數據庫更新為與當前模型匹配,因為存在掛起的更改並且禁用了自動遷移。將掛起的模型更改寫入基於代碼的遷移或啟用自動遷移。將 DbMigrationsConfiguration.AutomaticMigrationsEnabled 設置為 true 以啟用自動遷移。
您可使用 Add-Migration 命令將掛起的模型更改寫入基於代碼的遷移。
出現這個錯是因為我增加了一個表,要先 Add-Migration然后 Update-Database –Verbose 
 
Add-Migration InitialCreate –IgnoreChanges
無法生成顯式遷移,因為以下顯式遷移處於待定狀態: [201412050831298_AddUser]。請先應用待定的顯式遷移,然后再嘗試生成新的顯式遷移。
這時要先 Update-Database –Verbose 
 

關於遷移到MYSql的問題

首先,配置方式按照官方的(http://dev.mysql.com/doc/connector-net/en/connector-net-entityframework60.html)來寫,一步都不能少,否則絕壁報錯。
一些錯誤:

此操作要求連接到“master”數據庫。無法創建與“master”數據庫之間的連接,這是因為已打開原始數據庫連接,並且已從連接字符串中刪除憑據。請提供未打開的連接。 

上面這個是連接配置不干凈。遷移到mssqlsever上去了

The underlying provider does not support the type 'nvarchar(max)'.

這個也是項目的配置或dll有問題,排查一遍配置,然后清理,遷移
System.IO.FileLoadException: 未能加載文件或程序集“MySql.Data, Version=6.8.3.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d”或它的某一個依賴項。

找到的程序集清單定義與程序集引用不匹配。 (異常來自 HRESULT:0x80131040)
這個是mysql.entity依賴項目MySql.Data類型不匹配,當初我手賤把MySql.data升級到最新版6.9就會這樣,但實際上他的依賴項目不支持。但是顯示的時候,nuget依賴項只會要求最低版本限制而沒有最高版本限制,所以生成沒問題,運行的時候報錯,解決方案:
Install-Package MySql.Data   -Version 6.8.3 

 

未找到用於反序列化“MySql.Data.Types.MySqlConversionException”類型的對象的構造函數。

這個是因為我遷移的時候數據庫添加了datetime字段,造成既有數據的datetime為zero datetime((00/00/0000 00:00).我的解決方案是truncate表.
或者連接字符串末尾加上
Allow Zero Datetime=true

  第二種我沒試過.還有,我列舉的這種異常出現的原因具有特殊性,不具有代表性.

更改表主鍵的時候,提示表不存在 

這主要是 DropPrimaryKey這個方法引起的.
為了省事我就手動自己改數據庫表了,因為一直無法遷移.但是這樣查詢的時候,會引發下面一個問題

支持“XXXX”上下文的模型已在數據庫創建后發生更改

這是因為剛才我們沒有遷移成功.這時候,把剛才遷移的那個DbMigration類的up和down方法全注釋掉,然后Update-Database –Verbose 就可以了.verbose可免.

參考鏈接:

Entity Framework 6 中 Code First 的好處

Code First Migrations: Making __MigrationHistory not a system table
 

【遷移】—Entity Framework實例詳解

 

如何讓EF在創建數據庫時不生成__MigrationHistory表

 

 請教EF中Timestamp列的使用

 

解決C#獲取SQL的timestamp類型到程序中為byte[]類型的問題

 http://www.cnblogs.com/oppoic/p/ef_databasegeneratedoption_timestamp_concurrencycheck_complextype.html

 

附錄:nuget關於code first 遷移命令的幫助 

 

 

名稱 

Enable-Migrations 

摘要 

Enables Code First Migrations in a project. 

語法 

Enable-Migrations [-ContextTypeName <String>] [-EnableAutomaticMigrations] [-MigrationsDirectory <String>] [-ProjectName <String>] [-StartUpProjectName <String>] [-ContextProjectName <String>] [-ConnectionStringName <String>] [-Force] [-ContextA 
ssemblyName <String>] [-AppDomainBaseDirectory <String>] [<CommonParameters>] 

Enable-Migrations [-ContextTypeName <String>] [-EnableAutomaticMigrations] [-MigrationsDirectory <String>] [-ProjectName <String>] [-StartUpProjectName <String>] [-ContextProjectName <String>] -ConnectionString <String> -ConnectionProviderName < 
String> [-Force] [-ContextAssemblyName <String>] [-AppDomainBaseDirectory <String>] [<CommonParameters>] 

說明 

Enables Migrations by scaffolding a migrations configuration class in the project. If the 
target database was created by an initializer, an initial migration will be created (unless 
automatic migrations are enabled via the EnableAutomaticMigrations parameter). 

參數 

-ContextTypeName <String> 
Specifies the context to use. If omitted, migrations will attempt to locate a 
single context type in the target project. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-EnableAutomaticMigrations [<SwitchParameter>] 
Specifies whether automatic migrations will be enabled in the scaffolded migrations configuration. 
If omitted, automatic migrations will be disabled. 

是否必需? False 
位置? named 
默認值 False 
是否接受管道輸入? false 
是否接受通配符? False 

-MigrationsDirectory <String> 
Specifies the name of the directory that will contain migrations code files. 
If omitted, the directory will be named "Migrations". 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ProjectName <String> 
Specifies the project that the scaffolded migrations configuration class will 
be added to. If omitted, the default project selected in package manager 
console is used. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-StartUpProjectName <String> 
Specifies the configuration file to use for named connection strings. If 
omitted, the specified project's configuration file is used. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ContextProjectName <String> 
Specifies the project which contains the DbContext class to use. If omitted, 
the context is assumed to be in the same project used for migrations. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConnectionStringName <String> 
Specifies the name of a connection string to use from the application's 
configuration file. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConnectionString <String> 
Specifies the the connection string to use. If omitted, the context's 
default connection will be used. 

是否必需? True 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConnectionProviderName <String> 
Specifies the provider invariant name of the connection string. 

是否必需? True 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-Force [<SwitchParameter>] 
Specifies that the migrations configuration be overwritten when running more 
than once for a given project. 

是否必需? False 
位置? named 
默認值 False 
是否接受管道輸入? false 
是否接受通配符? False 

-ContextAssemblyName <String> 
Specifies the name of the assembly which contains the DbContext class to use. Use this 
parameter instead of ContextProjectName when the context is contained in a referenced 
assembly rather than in a project of the solution. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-AppDomainBaseDirectory <String> 
Specifies the directory to use for the app-domain that is used for running Migrations 
code such that the app-domain is able to find all required assemblies. This is an 
advanced option that should only be needed if the solution contains several projects 
such that the assemblies needed for the context and configuration are not all 
referenced from either the project containing the context or the project containing 
the migrations. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

<CommonParameters> 
此 Cmdlet 支持常見參數: Verbose、Debug、 
ErrorAction、ErrorVariable、WarningAction、WarningVariable、 
OutBuffer、PipelineVariable 和 OutVariable。有關詳細信息,請參閱 
about_CommonParameters ( http://go.microsoft.com/fwlink/?LinkID=113216)。

示例 1

C:\PS>Enable-Migrations 

# Scaffold a migrations configuration in a project with only one context 

示例 2 

C:\PS>Enable-Migrations -Auto 

# Scaffold a migrations configuration with automatic migrations enabled for a project 
# with only one context 

示例 3

C:\PS>Enable-Migrations -ContextTypeName MyContext -MigrationsDirectory DirectoryName 

# Scaffold a migrations configuration for a project with multiple contexts 
# This scaffolds a migrations configuration for MyContext and will put the configuration 
# and subsequent configurations in a new directory called "DirectoryName" 

備注 


備注 
若要查看示例,請鍵入: "get-help Enable-Migrations -examples". 
有關詳細信息,請鍵入: "get-help Enable-Migrations -detailed". 
若要獲取技術信息,請鍵入: "get-help Enable-Migrations -full".
 
 

 

名稱 

Add-Migration 

摘要 

Scaffolds a migration script for any pending model changes. 

語法 

Add-Migration [-Name] <String> [-Force] [-ProjectName <String>] [-StartUpProjectName <String>] [-ConfigurationTypeName <String>] [-ConnectionStringName <String>] [-IgnoreChanges] [-AppDomainBaseDirectory <String>] [<CommonParameters>] 

Add-Migration [-Name] <String> [-Force] [-ProjectName <String>] [-StartUpProjectName <String>] [-ConfigurationTypeName <String>] -ConnectionString <String> -ConnectionProviderName <String> [-IgnoreChanges] [-AppDomainBaseDirectory <String>] [<CommonParamet 
ers>] 

說明 

  Scaffolds a new migration script and adds it to the project.

參數 

-Name <String> 
Specifies the name of the custom script. 

是否必需? True 
位置? 1 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-Force [<SwitchParameter>] 
Specifies that the migration user code be overwritten when re-scaffolding an 
existing migration. 

是否必需? False 
位置? named 
默認值 False 
是否接受管道輸入? false 
是否接受通配符? False 

-ProjectName <String> 
Specifies the project that contains the migration configuration type to be 
used. If omitted, the default project selected in package manager console 
is used. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-StartUpProjectName <String> 
Specifies the configuration file to use for named connection strings. If 
omitted, the specified project's configuration file is used. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConfigurationTypeName <String> 
Specifies the migrations configuration to use. If omitted, migrations will 
attempt to locate a single migrations configuration type in the target 
project. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConnectionStringName <String> 
Specifies the name of a connection string to use from the application's 
configuration file. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConnectionString <String> 
Specifies the the connection string to use. If omitted, the context's 
default connection will be used. 

是否必需? True 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConnectionProviderName <String> 
Specifies the provider invariant name of the connection string. 

是否必需? True 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-IgnoreChanges [<SwitchParameter>] 
Scaffolds an empty migration ignoring any pending changes detected in the current model. 
This can be used to create an initial, empty migration to enable Migrations for an existing 
database. N.B. Doing this assumes that the target database schema is compatible with the 
current model. 

是否必需? False 
位置? named 
默認值 False 
是否接受管道輸入? false 
是否接受通配符? False 

-AppDomainBaseDirectory <String> 
Specifies the directory to use for the app-domain that is used for running Migrations 
code such that the app-domain is able to find all required assemblies. This is an 
advanced option that should only be needed if the solution contains several projects 
such that the assemblies needed for the context and configuration are not all 
referenced from either the project containing the context or the project containing 
the migrations. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

<CommonParameters> 
此 Cmdlet 支持常見參數: Verbose、Debug、 
ErrorAction、ErrorVariable、WarningAction、WarningVariable、 
OutBuffer、PipelineVariable 和 OutVariable。有關詳細信息,請參閱 
about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216)。

示例 1

  C:\PS>Add-Migration First
   
    # Scaffold a new migration named "First"

示例 2 

 C:\PS>Add-Migration First -IgnoreChanges
   
    # Scaffold an empty migration ignoring any pending changes detected in the current model.
    # This can be used to create an initial, empty migration to enable Migrations for an existing
    # database. N.B. Doing this assumes that the target database schema is compatible with the
    # current model.

示例 3

 

備注 

若要查看示例,請鍵入: "get-help Add-Migration -examples".
    有關詳細信息,請鍵入: "get-help Add-Migration -detailed".
    若要獲取技術信息,請鍵入: "get-help Add-Migration -full".

 

 

名稱 

 Update-Database

摘要 

Applies any pending migrations to the database.

語法 

 Update-Database [-SourceMigration <String>] [-TargetMigration <String>] [-Script] [-Force] [-ProjectName <String>] [-StartUpProjectName <String>] [-ConfigurationTypeName <String>] [-ConnectionStringName <String>] [-AppDomainBaseDirectory <String>] [<Common
    Parameters>]
   
    Update-Database [-SourceMigration <String>] [-TargetMigration <String>] [-Script] [-Force] [-ProjectName <String>] [-StartUpProjectName <String>] [-ConfigurationTypeName <String>] -ConnectionString <String> -ConnectionProviderName <String> [-AppDomainBaseD
    irectory <String>] [<CommonParameters>]

說明 

 Updates the database to the current model by applying pending migrations.

參數 

-SourceMigration <String> 
Only valid with -Script. Specifies the name of a particular migration to use 
as the update's starting point. If omitted, the last applied migration in 
the database will be used. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-TargetMigration <String> 
Specifies the name of a particular migration to update the database to. If 
omitted, the current model will be used. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-Script [<SwitchParameter>] 
Generate a SQL script rather than executing the pending changes directly. 

是否必需? False 
位置? named 
默認值 False 
是否接受管道輸入? false 
是否接受通配符? False 

-Force [<SwitchParameter>] 
Specifies that data loss is acceptable during automatic migration of the 
database. 

是否必需? False 
位置? named 
默認值 False 
是否接受管道輸入? false 
是否接受通配符? False 

-ProjectName <String> 
Specifies the project that contains the migration configuration type to be 
used. If omitted, the default project selected in package manager console 
is used. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-StartUpProjectName <String> 
Specifies the configuration file to use for named connection strings. If 
omitted, the specified project's configuration file is used. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConfigurationTypeName <String> 
Specifies the migrations configuration to use. If omitted, migrations will 
attempt to locate a single migrations configuration type in the target 
project. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConnectionStringName <String> 
Specifies the name of a connection string to use from the application's 
configuration file. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConnectionString <String> 
Specifies the the connection string to use. If omitted, the context's 
default connection will be used. 

是否必需? True 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConnectionProviderName <String> 
Specifies the provider invariant name of the connection string. 

是否必需? True 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-AppDomainBaseDirectory <String> 
Specifies the directory to use for the app-domain that is used for running Migrations 
code such that the app-domain is able to find all required assemblies. This is an 
advanced option that should only be needed if the solution contains several projects 
such that the assemblies needed for the context and configuration are not all 
referenced from either the project containing the context or the project containing 
the migrations. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

<CommonParameters> 
此 Cmdlet 支持常見參數: Verbose、Debug、 
ErrorAction、ErrorVariable、WarningAction、WarningVariable、 
OutBuffer、PipelineVariable 和 OutVariable。有關詳細信息,請參閱 
about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216)。

示例 1

  C:\PS>Update-Database      
    # Update the database to the latest migration     
    

示例 2 

    C:\PS>Update-Database -TargetMigration Second      
    # Update database to a migration named "Second"
    # This will apply migrations if the target hasn't been applied or roll back migrations
    # if it has

示例 3

      C:\PS>Update-Database -Script      
    # Generate a script to update the database from it's current state  to the latest migration     

示例4

 C:\PS>Update-Database -Script -SourceMigration Second -TargetMigration First
   
    # Generate a script to migrate the database from a specified start migration
    # named "Second" to a specified target migration named "First"
    

示例5

  C:\PS>Update-Database -Script -SourceMigration $InitialDatabase
   
    # Generate a script that can upgrade a database currently at any version to the latest version.
    # The generated script includes logic to check the __MigrationsHistory table and only apply changes
    # that haven't been previously applied.

示例6

 C:\PS>Update-Database -TargetMigration $InitialDatabase
   
    # Runs the Down method to roll-back any migrations that have been applied to the database

備注 

若要查看示例,請鍵入: "get-help Update-Database -examples".
    有關詳細信息,請鍵入: "get-help Update-Database -detailed".
    若要獲取技術信息,請鍵入: "get-help Update-Database -full".
 

 

 

 

 

 

名稱 

 Get-Migrations

摘要 

Displays the migrations that have been applied to the target database.

語法 

Get-Migrations [-ProjectName <String>] [-StartUpProjectName <String>] [-ConfigurationTypeName <String>] [-ConnectionStringName <String>] [-AppDomainBaseDirectory <String>] [<CommonParameters>]
   
    Get-Migrations [-ProjectName <String>] [-StartUpProjectName <String>] [-ConfigurationTypeName <String>] -ConnectionString <String> -ConnectionProviderName <String> [-AppDomainBaseDirectory <String>] [<CommonParameters>]
    

說明 

  Displays the migrations that have been applied to the target database.
    

參數 

-ProjectName <String> 
Specifies the project that contains the migration configuration type to be 
used. If omitted, the default project selected in package manager console 
is used. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-StartUpProjectName <String> 
Specifies the configuration file to use for named connection strings. If 
omitted, the specified project's configuration file is used. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConfigurationTypeName <String> 
Specifies the migrations configuration to use. If omitted, migrations will 
attempt to locate a single migrations configuration type in the target 
project. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConnectionStringName <String> 
Specifies the name of a connection string to use from the application's 
configuration file. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConnectionString <String> 
Specifies the the connection string to use. If omitted, the context's 
default connection will be used. 

是否必需? True 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-ConnectionProviderName <String> 
Specifies the provider invariant name of the connection string. 

是否必需? True 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

-AppDomainBaseDirectory <String> 
Specifies the directory to use for the app-domain that is used for running Migrations 
code such that the app-domain is able to find all required assemblies. This is an 
advanced option that should only be needed if the solution contains several projects 
such that the assemblies needed for the context and configuration are not all 
referenced from either the project containing the context or the project containing 
the migrations. 

是否必需? False 
位置? named 
默認值 
是否接受管道輸入? false 
是否接受通配符? False 

<CommonParameters> 
此 Cmdlet 支持常見參數: Verbose、Debug、 
ErrorAction、ErrorVariable、WarningAction、WarningVariable、 
OutBuffer、PipelineVariable 和 OutVariable。有關詳細信息,請參閱 
about_CommonParameters ( http://go.microsoft.com/fwlink/?LinkID=113216)。

示例 1

 

示例 2 

 

示例 3

 

備注 

  若要查看示例,請鍵入: "get-help Get-Migrations -examples".
    有關詳細信息,請鍵入: "get-help Get-Migrations -detailed".
    若要獲取技術信息,請鍵入: "get-help Get-Migrations -full".
 
 
 來自get-help  EntityFramework.
其實這些可選參數我看了一下,在一個項目一個dbcontext的話不需要用到.因為這些參數大半是指定命名空間(可以用下拉框取代),連接字符串,文件目錄,下下文類名這類的.
但是我有一個困惑就是,code first的時候,至上而下的遷移怎么做(從數據庫更新實體)?
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM