加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

是否有命令检查实体框架中是否存在数据库?

发布时间:2020-12-12 16:23:54 所属栏目:MsSql教程 来源:网络整理
导读:我可能措辞不好但在我使用的global.asx文件中 if (System.Diagnostics.Debugger.IsAttached) { var test = new TestDbSeeder(App_Start.NinjectWebCommon.UcxDbContext); test.seed(); } 这将检查调试器是否已连接并运行我的测试播种器,以便我的验收测试始终
我可能措辞不好但在我使用的global.asx文件中
if (System.Diagnostics.Debugger.IsAttached)
        {
            var test = new TestDbSeeder(App_Start.NinjectWebCommon.UcxDbContext);
            test.seed();
       }

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

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

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

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

解决方法

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文件中……

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读