实体框架代码优先检查数据库是否存在 [英] Entity Framework Code First check Database exist

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

问题描述

首先在实体框架代码中,我要在创建数据库之前检查数据库是否存在。
首先在代码中,当我调用 Entities dc = new Entities()时,它将转到OnModelCreating并生成数据库。我该如何首先检查数据库是否存在于实体框架代码中?

In Entity Framework Code first i want to check database is exist before create Database. In code first when i call Entities dc = new Entities() then it goes to OnModelCreating and generate Database. How can i check if the Database exists in Entity framework Code first?

推荐答案

您可以执行以下操作:

using(var dbContext = new MyContext())
{
    if (!dbContext.Database.Exists())
        dbContext.Database.Create();
}

编辑:

遵循colegue的建议,此代码的含义非常简单:假设未将上下文构造函数设置为创建数据库,因此在发送任何数据库操作之前,您可以检查它是否存在,如果不存在,则可以创建一个新数据库连接字符串参数是创建的规则。

Following the colegue sugestion, the meaning of this code is very simple: Supose your context constructor is not set to create the database, so before sending any database operations, you can check if it exists, if not, you can create a new one with the connection string parameters being the rules for the creation.

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

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