C# entity framework MVC second run error

103 views Asked by At

I am creating db and initializing data with code below, if DB doesnt exist, it creates db and populate it, when I run application second time I get error

Cannot drop database "aspnet-app" because it is currently in use.

Application_start, with initializations

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        WebApiConfig.Register(GlobalConfiguration.Configuration);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        Database.SetInitializer(new ComponentDbInitialize());
        ComputerContext context = new ComputerContext();
        context.Database.Initialize(true); //here it fails on second run
        context.SaveChanges();
    }

ComputerContext

 public ComputerContext():base("name=Default")
    {
    }
    public DbSet<Computer> Computers { get; set; }
    public DbSet<Motherboard> Motherboards { get; set; }
    public DbSet<CPU> CPUs { get; set; }
    public DbSet<Case> Cases { get; set; }
    public DbSet<HDD> HDDs { get; set; }
    public DbSet<RAM> RAMs { get; set; }
    public DbSet<GPU> GPUs { get; set; }
    public DbSet<PSU> PSUs { get; set; }
}

Initialize class

public class ComponentDbInitialize : DropCreateDatabaseAlways<ComputerContext>
{
    protected override void Seed(ComputerContext context)
    {
        GetCpu().ForEach(p => context.CPUs.Add(p));
        GetGpu().ForEach(p => context.GPUs.Add(p));
        GetCase().ForEach(p => context.Cases.Add(p));
        GetHdd().ForEach(p => context.HDDs.Add(p));
        GetMb().ForEach(p => context.Motherboards.Add(p));
        GetPsu().ForEach(p => context.PSUs.Add(p));
        GetRam().ForEach(p => context.RAMs.Add(p));
        context.SaveChanges();
    }
private static List<CPU> GetCpu() .....
private static List<GPU> GetGpu().....
private static List<HDD> GetHdd()....
private static List<Case> GetCase()....
private static List<Motherboard> GetMb()....
private static List<PSU> GetPsu()....
private static List<RAM> GetRam()....

I get same error even with

context.Database.Initialize(false);

Thank you for any help/advice

1

There are 1 answers

3
DavidG On BEST ANSWER

Your initialiser is using the DropCreateDatabaseAlways class which, as it suggests, drops that database every time the application is initialised.

Instead perhaps you could use CreateDatabaseIfNotExists or DropCreateDatabaseIfModelChanges:

public class ComponentDbInitialize : CreateDatabaseIfNotExists<ComputerContext>
{

}