EF6 - 运行没有种子的Update-Database命令

Raú*_*año 9 .net c# migration entity-framework database-migration

我正在使用实体框架6,我正在使用迁移.我已经使用初始迁移创建了数据库.现在我已对模型进行了更改并且上下文已更改,我想更新数据库但是......当我再次尝试运行Database-Update命令时,种子也在运行,这会因为某些数据再次插入而导致错误.

那么,如何在Update-Database不运行种子方法的情况下运行命令?


很难相信EF没有任何简单的选择-No-Seed.其他ORM的确如此安全.

Aug*_*eto 10

来源代码DbMigrationsConfiguration<TContext>:

/// <summary>
    /// Runs after upgrading to the latest migration to allow seed data to be updated.
    /// 
    /// </summary>
    /// 
    /// <remarks>
    /// Note that the database may already contain seed data when this method runs. This means that
    ///             implementations of this method must check whether or not seed data is present and/or up-to-date
    ///             and then only make changes if necessary and in a non-destructive way. The
    ///             <see cref="M:System.Data.Entity.Migrations.DbSetMigrationsExtensions.AddOrUpdate``1(System.Data.Entity.IDbSet{``0},``0[])"/>
    ///             can be used to help with this, but for seeding large amounts of data it may be necessary to do less
    ///             granular checks if performance is an issue.
    ///             If the <see cref="T:System.Data.Entity.MigrateDatabaseToLatestVersion`2"/> database
    ///             initializer is being used, then this method will be called each time that the initializer runs.
    ///             If one of the <see cref="T:System.Data.Entity.DropCreateDatabaseAlways`1"/>, <see cref="T:System.Data.Entity.DropCreateDatabaseIfModelChanges`1"/>,
    ///             or <see cref="T:System.Data.Entity.CreateDatabaseIfNotExists`1"/> initializers is being used, then this method will not be
    ///             called and the Seed method defined in the initializer should be used instead.
    /// 
    /// </remarks>
    /// <param name="context">Context to be used for updating seed data. </param>
Run Code Online (Sandbox Code Playgroud)

基本上,除了实现"添加或更新"逻辑之外,没有其他选项,因为每次使用初始化程序后都会执行Seed方法.

AddOrUpdate扩展方法对此很有用,但在某些情况下我也使用了它:

            if (!context.Entities.Any())
            {
                 // Seed
            }
Run Code Online (Sandbox Code Playgroud)

  • 向下投票是因为如果没有未决的迁移,那么说不会执行Seed方法是完全错误的 (2认同)