EF Code First 的自定义初始化策略,不会删除表来添加列
最新的 EF Code First NuGet 包附带了名为 DontDropDbJustCreateTablesIfModelChanged
的 IDatabaseInitializer
自定义实现。顾名思义,当检测到模型更改时,它不会删除并重新创建整个数据库,而只是删除并重新创建表。
假设我有这个模型类:
public class User
{
public string Username { get; set; }
// This property is new; the model has changed!
public string OpenID { get; set; }
}
如何实现一个也不会删除任何表的IDatabaseInitializer
。在这种情况下,它只会向 User 表添加一个 OpenID
列吗?
The latest EF Code First NuGet package comes with a custom implementation of IDatabaseInitializer
called DontDropDbJustCreateTablesIfModelChanged
. As the name implies, when a model change is detected, it will not drop and recreate the whole database, just drop and recreate the tables.
Say I have this model class:
public class User
{
public string Username { get; set; }
// This property is new; the model has changed!
public string OpenID { get; set; }
}
How would one go about implementing an IDatabaseInitializer
that doesn't drop any tables either. In this case, it would just add an OpenID
column to the User table?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这是SQL的问题。因此,对于 SQL Server,您可以编写如下内容:
但以同样的方式,您可以执行此类脚本,而无需将其添加到您的应用程序中,我认为这是更好的方法。
I think it is a matter of SQL. So for SQL Server you can write something like:
But in the same way you can execute such script without adding it to your application which I think is much better approach.
使用当前版本的 Code First,您不能简单地修改架构并保留表中可能拥有的任何数据。如果维护数据(例如参考数据/查找表)对于此版本很重要,您可以创建自己的初始化程序并重写 Seed 方法来填充您的表
,然后在您的 Application_Start 中使用它:
我相信 EF 目前正在解决这个问题团队,但在 Code First 发布时尚未准备好发布。您可以在此处查看预览:代码优先迁移
With the current version of Code First, you cannot simply amend your schema and preserve any data that you might have in your tables. If maintaining data, such as reference data / lookup tables is important with this release you can create your own Initializer and override the Seed method to populate your tables
And then use this in your Application_Start:
I believe that this is being addressed currently by the EF Team, but wasn't ready for release at the time the Code First drop came out. You can see a preview here: Code First Migrations