Is there a command to check to see if a database exists from Entity Framework?

后端 未结 2 1542
天涯浪人
天涯浪人 2020-12-20 15:23

I may have worded the question poorly but in my global.asx file i use

 if (System.Diagnostics.Debugger.IsAttached)
        {
            var test = new Test         


        
2条回答
  •  盖世英雄少女心
    2020-12-20 15:27

    Will the Database.Exists method work for you?

    if (!dbContext.Database.Exists())
        dbContext.Database.Create();
    

    Edit #1 to answer comment

    public class DatabaseBootstrapper
    {
        private readonly MyContext context;
    
        public DatabaseBootstrapper(MyContext context)
        {
            this.context = context;
        }
    
        public void Configure()
        {
            if (context.Database.Exists())
                return;
    
            context.Database.Create();
            var seeder = new Seeder(context);
            seeder.SeedDatabase();
        }
    }
    

    That should do exactly what you want. In your global.asax file...

    public void Application_Start()
    {
        var context = ...; // get your context somehow.
        new DatabaseBootstrapper(context).Configure();
    }
    

提交回复
热议问题