简体   繁体   English

EF 4.1 Code First - 添加列

[英]EF 4.1 Code First - add column

I have my database already set, I want to add a new field to the model, a new column to the table, is there a way I can do this without losing all my data? 我已经设置了我的数据库,我想在模型中添加一个新字段,这是表的新列,有没有办法可以做到这一点而不会丢失所有数据? Normally if you delete the DB it will recreate everything automatically but I don't want to lose the data. 通常,如果删除数据库,它将自动重新创建所有内容,但我不想丢失数据。 I'm using SQL Server 2008 as database. 我正在使用SQL Server 2008作为数据库。

You will need to use EF Migrations to add the new column to your database. 您需要使用EF迁移将新列添加到数据库中。 You can read more about EF Migrations here and here . 您可以在此处此处阅读有关EF迁移的更多信息。

If you're using code first, I've always just added the column to the database manually in situations like that. 如果您首先使用代码,我总是在这种情况下手动将列添加到数据库中。 Unfortunately, there is no simple way to automate incremental model updates with Code First. 不幸的是,没有简单的方法可以使用Code First自动化增量模型更新。

For example, one of EF Code First's own errors even specify manual update as the best option: 例如,EF Code First自身的错误之一甚至将手动更新指定为最佳选项:

The model backing the 'your context' context has changed since the database was created. 自创建数据库以来,支持“您的上下文”上下文的模型已更改。 Either manually delete/update the database, or call Database SetInitializer with an IDatabaseInitializer instance. 手动删除/更新数据库,或使用IDatabaseInitializer实例调用Database SetInitializer。 For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data. 例如,DropCreateDatabaseIfModelChanges策略将自动删除并重新创建数据库,并可选择使用新数据对其进行种子设定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM