zoukankan      html  css  js  c++  java
  • 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的时候,至上而下的迁移怎么做(从数据库更新实体)?
     
  • 相关阅读:
    Beans
    HDU 1175 连连看
    HDU 1241 Oil Deposits dfs && bfs
    HDU1312:Red and Black
    背包问题
    canvas 和 svg
    前端性能优化---DOM操作
    四种常见的 POST 提交数据方式
    [转]浏览器缓存详解: expires, cache-control, last-modified, etag详细说明
    URL和URI
  • 原文地址:https://www.cnblogs.com/zeusro/p/4241934.html
Copyright © 2011-2022 走看看