EF6

编程入门 行业动态 更新时间:2024-10-20 03:30:36
本文介绍了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

本文发布于:2023-11-15 03:51:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1590889.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!