每个实体框架数据库迁移后如何访问上下文

编程入门 行业动态 更新时间:2024-10-25 12:26:44
本文介绍了每个实体框架数据库迁移后如何访问上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 当我添加迁移时,我可以使用Up / Down方法获取适当的DbMigration类,我可以在其中进行模式更改(使用Sql()方法)可以使数据/内容更改

我希望能够使用数据库上下文进行每次迁移的内容更改。我明白我可以在配置类中使用Seed方法,但我的理解是我只能使用初始化器连接一个配置。

我更喜欢有一个UpCompleted()/ DownCompleted()方法,可以在迁移完成后提供对db上下文的访问。这将使得以比使用Sql()方法更容易出错的方式编写增量数据/上下文更改脚本。

我错过了什么?这是可能吗?

谢谢!

解决方案

真正的工作,因为上下文只有你最近的模型 - 只能用于访问数据库一旦最近的迁移运行(这实际上是种子实现)。

关于这个想法如何中断的一个例子,如果你将一个属性从一个类移动到另一个类,那么来自旧的迁移的种子逻辑将不再编译。但是您不能更改它以使用新的属性,因为相应的列不会存在于数据库中。

如果要编写这种种子/数据操作逻辑,您需要将其放在Up / Down方法的末尾,并使用Sql方法使用raw SQL执行。

〜Rowan

When I Add-Migration, I get the appropriate DbMigration class with the Up / Down methods, where I am able to make schema changes and (with the use of the Sql() method) can make data/content changes as well.

I'd like to be able to make content changes per migration using the database context. I understand that I could use the Seed method in a Configuration class, but my understanding is that I can only wire up one Configuration with my initializer.

I'd prefer to have a UpCompleted()/DownCompleted() methods that would provide access to the db context after the migration completed. This would enable writing incremental data/context change "scripts" in a manner that would be less prone to errors than using the Sql() method.

Am I missing something? Is this possible?

Thanks!

解决方案

That doesn't really work because the context only has your most recent model - which can only be used to access the database once the most recent migration has run (which is effectively what Seed achieves).

For an example of how this idea breaks, if you moved a property from one class to another then seed logic from older migrations would no longer compile. But you couldn't change it to use the new property because the corresponding column wouldn't exist in the database yet.

If you want to write this kind of seed/data-manipulation logic, you need to put it at the end of the Up/Down methods and use the Sql method to perform it using raw SQL.

~Rowan

更多推荐

每个实体框架数据库迁移后如何访问上下文

本文发布于:2023-05-26 16:23:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/265269.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:上下文   实体   框架   数据库

发布评论

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

>www.elefans.com

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