Database in use error with Entity Framework 4 Code First

后端 未结 6 664
借酒劲吻你
借酒劲吻你 2020-12-02 09:39

I have an MVC3 and EF 4 Code First application, which is configured to change the DB when the model changes, by setting the DB Initializer to a DropCreateDatabaseIfMod

6条回答
  •  广开言路
    2020-12-02 10:23

    I realize this is dated but I couldn't get the accepted solution working so I rolled a quick solution...

    using System;
    using System.Data.Entity;
    
    namespace YourCompany.EntityFramework
    {
        public class DropDatabaseInitializer : IDatabaseInitializer where T : DbContext, new()
        {
            public DropDatabaseInitializer(Action seed = null)
            {
                Seed = seed ?? delegate {};
            }
    
            public Action Seed { get; set; }
    
            public void InitializeDatabase(T context)
            {
                if (context.Database.Exists())
                {
                    context.Database.ExecuteSqlCommand("ALTER DATABASE [" + context.Database.Connection.Database + "] SET SINGLE_USER WITH ROLLBACK IMMEDIATE");
                    context.Database.ExecuteSqlCommand("USE master DROP DATABASE [" + context.Database.Connection.Database + "]");
                }
    
                context.Database.Create();
    
                Seed(context);
            }
        }
    }
    

    This works for me and supports seeding easily.

提交回复
热议问题