每个实体框架数据库迁移后如何访问上下文 [英] How to access context after each Entity Framework db migration

查看:132
本文介绍了每个实体框架数据库迁移后如何访问上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我添加迁移时,我可以使用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

这篇关于每个实体框架数据库迁移后如何访问上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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