Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

c# - How to recreate database in EF if my model changes?

I created a DbContext like so :

   public class myDB : DbContext
   {
     public DbSet<Party> Parties { get; set; }
     public DbSet<Booking> Bookings { get; set; }
   }

This generated my DataBase and the two tables above..Great

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

I'm aware of the fixes for this using modelbuilder.IncludeMetadataInDatabase = false; and Database.SetInitializer<ClubmansGuideDB>(null);

1) What's the correct way to add my new classes to the context and have them generated in the DataBase?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe you're looking for:

Database.SetInitializer<ClubmansGuideDB>(new DropCreateDatabaseIfModelChanges<ClubmansGuideDB>());

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...