是否有命令检查实体框架中是否存在数据库? [英] Is there a command to check to see if a database exists from Entity Framework?

查看:97
本文介绍了是否有命令检查实体框架中是否存在数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可能措辞不佳,但我在global.asx文件中使用

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

 if (System.Diagnostics.Debugger.IsAttached)
        {
            var test = new TestDbSeeder(App_Start.NinjectWebCommon.UcxDbContext);
            test.seed();
       }

这将检查是否已连接调试器并运行我的测试种子机,以便我的验收测试始终会通过。

This checks to see if the debugger is attached and runs my test seeder so that my acceptance tests always pass.

我需要检查数据库是否也存在,如果不存在,请先运行此代码:

I need to check to see if the database exists as well and if not run this code first:

  var test2 = new DataSeeder();
  test2.Seed(App_Start.NinjectWebCommon.UcxDbContext);

此dataseeder是必须始终存在于数据库中的实际数据。是否有命令检查数据库是否存在,以便我可以运行该代码块。谢谢!

This dataseeder is the actual data that has to always be in the database. Is there a command to check if the database exists so that I can run that code block. Thanks!

推荐答案

Database.Exists 方法对您有用吗?

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

编辑#1以回答评论

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();
    }
}

这应该可以完全满足您的要求。在您的global.asax文件中...

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();
}

这篇关于是否有命令检查实体框架中是否存在数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆