如何重建数据库中的EF如果我的模型变化? [英] How to recreate database in EF if my model changes?
问题描述
我创建了一个的DbContext像这样:
I created a DbContext like so :
public class myDB : DbContext
{
public DbSet<Party> Parties { get; set; }
public DbSet<Booking> Bookings { get; set; }
}
这生成我的数据库和两个表above..Great
This generated my DataBase and the two tables above..Great
然后我决定再增加DbSet到混合&放大器;我得到了一个错误:
I then decided to add another DbSet into the mix & I got an error:
模型支持的党背景已经改变,因为在创建数据库
the model backing the 'Party' context has changed since the database was created
我知道了修正该使用 modelbuilder.IncludeMetadataInDatabase = FALSE;
和 Database.SetInitializer&LT; ClubmansGuideDB&GT;(NULL);
I'm aware of the fixes for this using modelbuilder.IncludeMetadataInDatabase = false;
and Database.SetInitializer<ClubmansGuideDB>(null);
1)什么是增加我的新类的背景下,并在数据库中生成正确的方法是什么?
1) What's the correct way to add my new classes to the context and have them generated in the DataBase?
2)在我徒劳的努力来解决这个自己,我删除了表,并试图重新运行,但没有成功,然后我删除了完整的数据库,并重新运行,它不会重新生成数据库应用程序。我如何从头开始 - 是有一些缓存的地方
2) In my futile attempts to solve this myself I deleted the tables and tried to re-run the app with no success I then deleted the full database and re-run and it doesn't re-generate the DB. How can I start from scratch - is there some cache somewhere?
推荐答案
我相信你要找的:
Database.SetInitializer<ClubmansGuideDB>(new DropCreateDatabaseIfModelChanges<ClubmansGuideDB>());
由于EF 4.1及以上。
As of EF 4.1 and above.
请注意,这里假设你有权限甚至删除您的数据库。我这样做是当地为便于开发,但在分期禁用/生产(我做了手动模式进行比较,并把我的变化)。
Note that this assumes you have permission to even drop your database. I do this locally for ease of development but disable it in staging/production (I do a manual Schema Compare and push my changes).
顺便说一句,进行测试,如果你需要强制重新创建数据库,你可以这样做:
By the way, for testing, if you need to force recreate the database, you can do:
using (var context = new ClubmansGuideDB()) {
context.Database.Initialize(force: true);
}
(使用
如果您还没有一个引用您的数据库)
(using
if you don't already have a reference to your DB)
这篇关于如何重建数据库中的EF如果我的模型变化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!