存储库内部Database.SetInitializer< ArContext>(null)的用途? [英] purpose of Database.SetInitializer<ArContext>(null) inside of repository?

查看:71
本文介绍了存储库内部Database.SetInitializer< ArContext>(null)的用途?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架,并且在我的上下文中是从DbContext继承的。

I am using entity framework and in my context inheriting from DbContext.

public class MyContext : DbContext, IMyContext
{
    static MyContext()
    {
        Database.SetInitializer<MyContext>(null);
    }
    //other stuff
}

此行的目的是什么?

Database.SetInitializer<ArContext>(null)


推荐答案

您可以关闭应用程序的数据库初始化程序。在不希望丢失现有数据的生产环境中,在这种情况下,可以关闭初始化程序,如下所示。

You can turn off the DB initializer of your application. On the production environment where you don't want to lose the existing data.In such scenario you can turn off the initializer, as shown below.

 public MyContext()
    {
        Database.SetInitializer<MyContext>(null);//Disable initializer
    }

有四种不同的数据库初始化策略:



  1. CreateDatabaseIfNotExists:。这是默认的初始化程序。就像
    的名字所暗示的那样,如果按照
    的配置不存在,它将创建数据库。但是,如果您更改模型类,然后使用此初始化程序运行
    应用程序,则会抛出
    异常。

  2. DropCreateDatabaseIfModelChanges:如果您的模型类(实体
    类)已更改,则此初始化程序将删除现有的
    数据库并创建一个新数据库。因此,当模型类更改时,您不必担心
    维护数据库架构。

  3. DropCreateDatabaseAlways:顾名思义,这每次运行应用程序时,初始化器
    都会删除现有数据库,而无论模型类是否已更改,
    都将删除它。当您想要新的数据库时,每次运行
    应用程序时(例如在开发应用程序时),此
    都会很有用。

  4. 自定义数据库初始化程序:,如果以上任何一项都不满足您的要求
    ,或者您想执行其他一些初始化数据库
    的过程,则还可以创建自己的自定义
    初始化程序使用上述初始化程序。

  1. CreateDatabaseIfNotExists: This is default initializer. As the name suggests, it will create the database if none exists as per the configuration. However, if you change the model class and then run the application with this initializer, then it will throw an exception.
  2. DropCreateDatabaseIfModelChanges: This initializer drops an existing database and creates a new database, if your model classes (entity classes) have been changed. So you don't have to worry about maintaining your database schema, when your model classes change.
  3. DropCreateDatabaseAlways: As the name suggests, this initializer drops an existing database every time you run the application, irrespective of whether your model classes have changed or not. This will be useful, when you want fresh database, every time you run the application, like while you are developing the application.
  4. Custom DB Initializer: You can also create your own custom initializer, if any of the above doesn't satisfy your requirements or you want to do some other process that initializes the database using the above initializer.


参考文献: 数据库初始化策略

Reference : Database Initialization Strategies

这篇关于存储库内部Database.SetInitializer&lt; ArContext&gt;(null)的用途?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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