How to recreate database in EF if my model changes?

前端 未结 3 1440
慢半拍i
慢半拍i 2020-12-10 18:55

I created a DbContext like so :

   public class myDB : DbContext
   {
     public DbSet Parties { get; set; }
     public DbSet B         


        
相关标签:
3条回答
  • 2020-12-10 19:32

    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)

    0 讨论(0)
  • 2020-12-10 19:46

    Try putting this in your Global.asax.cs Application_Start() method.

    Database.SetInitializer<DatabaseContext>(null);
    

    To reset the database from scratch on app run make a class like this

    //Where myDB is your context
    public class EntityBase: DropCreateDatabaseAlways<myDB>
    {
    
    } 
    

    Then in your Application_Start() method you can do this

    Database.SetInitializer(new EntityBase());
    
    0 讨论(0)
  • 2020-12-10 19:48

    You can let the Entity Framework recreate the whole database by using a Database Initializer or if you want to migrate data you can look at the Code First Migrations

    The following would recreate your database when the model changes:

    Database.SetInitializer<myDB>(new DropCreateDatabaseIfModelChanges<myDB>());
    
    0 讨论(0)
提交回复
热议问题