EF6 - 无种子运行Update-Database命令 [英] EF6 - Run Update-Database Command without seeds

查看:344
本文介绍了EF6 - 无种子运行Update-Database命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架6,我正在使用迁移。我已经使用初始迁移创建了数据库。现在我已经对模型做了修改,并且上下文已经改变了,我想要更新数据库BUT ...
当我再次尝试运行数据库更新命令种子也在运行,这会导致错误,因为一些数据被再次插入。

I'm Using Entity Framework 6 and I'm using migrations. I have already created the database using an initial migration. Now I have done changes to the Model and the context has changed, and I want to update the database BUT... When I try to run again the Database-Update command the seeds are also running too, and this bring errores due some data is inserted again.

很难相信EF没有任何简单的选项,如 -No-Seed

It is hard to believe that EF doesn't have any simple option like -No-Seed for that. I'm almost secure that other ORMs does.

推荐答案

从源代码 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>

基本上,您没有其他选项来实现添加或更新逻辑,因为种子方法将在使用初始化程序后每次执行。

Basically, you don't have another option than implement an "add or update" logic because the Seed method will be executed each time after the initializer is used.

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

The AddOrUpdate extension method is useful for this, but I have also used this in some cases:

            if (!context.Entities.Any())
            {
                 // Seed
            }

这篇关于EF6 - 无种子运行Update-Database命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆