gpt4 book ai didi

c# - EF6 - 运行不带种子的更新数据库命令

转载 作者:太空狗 更新时间:2023-10-29 17:39:06 25 4
gpt4 key购买 nike

我正在使用 Entity Framework 6 并且正在使用迁移。我已经使用初始迁移创建了数据库。现在我已经对模型进行了更改并且上下文发生了变化,我想更新数据库但是......当我尝试再次运行 Database-Update 命令时,种子也在运行,并且由于再次插入了一些数据而导致错误。

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


很难相信 EF 没有像 -No-Seed 这样的简单选项。我几乎可以肯定其他 ORM 确实如此。

最佳答案

来自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>

基本上,除了实现“添加或更新”逻辑之外别无选择,因为每次使用初始化程序后都会执行 Seed 方法。

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

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

关于c# - EF6 - 运行不带种子的更新数据库命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28635377/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com