Database Initialization Strategies in Code-First:

You already created a database after running your Code-First application the first time, but what about the second time onwards?? Will it create a new database every time you run the application? What about the production environment? How do you alter the database when you change your domain model? To handle these scenarios, you have to use one of the database initialization strategies.

There are four different database initialization strategies:

  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.

To use one of the above DB initialization strategies, you have to set the DB Initializer using Database class in Context class, as shown below:

public class SchoolDBContext: DbContext
{ public SchoolDBContext(): base("SchoolDBConnectionString")
{
Database.SetInitializer<SchoolDBContext>(new CreateDatabaseIfNotExists<SchoolDBContext>()); //Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseIfModelChanges<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new DropCreateDatabaseAlways<SchoolDBContext>());
//Database.SetInitializer<SchoolDBContext>(new SchoolDBInitializer());
}
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
}

You can also create your custom DB initializer, by inheriting one of the initializers, as shown below:

public class SchoolDBInitializer :  CreateDatabaseIfNotExists<SchoolDBContext>
{
protected override void Seed(SchoolDBContext context)
{
base.Seed(context);
}
}

As you can see in the above code, we have created a new class SchoolDBInitializer, which is derived from DropCreateDatabaseAlways initializer.

Set db initializer in the configuration file:

You can also set db initializer in the configuration file. For example, to set default initializer in app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DatabaseInitializerForType SchoolDataLayer.SchoolDBContext, SchoolDataLayer"
value="System.Data.Entity.DropCreateDatabaseAlways`1[[SchoolDataLayer.SchoolDBContext, SchoolDataLayer]], EntityFramework" />
</appSettings>
</configuration>

You can set custom DB initializer, as follows:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="DatabaseInitializerForType SchoolDataLayer.SchoolDBContext, SchoolDataLayer"
value="SchoolDataLayer.SchoolDBInitializer, SchoolDataLayer" />
</appSettings>
</configuration>

This way, you can use DB initialization strategy for your application.

Entity Framework Code-First(17):Database Initialization Strategy的更多相关文章

  1. Entity Framework Tutorial Basics(13):Database First

    Database First development with Entity Framework: We have seen this approach in Create Entity Data M ...

  2. Entity Framework Tutorial Basics(17):DBSet Class

    DBSet Class DBSet class represents an entity set that is used for create, read, update, and delete o ...

  3. Entity Framework Code first(转载)

    一.Entity Framework Code first(代码优先)使用过程 1.1Entity Framework 代码优先简介 不得不提Entity Framework Code First这个 ...

  4. Entity Framework Code First (三)Data Annotations

    Entity Framework Code First 利用一种被称为约定(Conventions)优于配置(Configuration)的编程模式允许你使用自己的 domain classes 来表 ...

  5. Entity Framework Code First (二)Custom Conventions

    ---------------------------------------------------------------------------------------------------- ...

  6. Entity Framework Code First (一)Conventions

    Entity Framework 简言之就是一个ORM(Object-Relational Mapper)框架. Code First 使得你能够通过C#的类来描述一个模型,模型如何被发现/检测就是通 ...

  7. Entity Framework Tutorial Basics(4):Setup Entity Framework Environment

    Setup Entity Framework Environment: Entity Framework 5.0 API was distributed in two places, in NuGet ...

  8. Entity Framework Tutorial Basics(11):Code First

    Code First development with Entity Framework: Entity Framework supports three different development ...

  9. Entity Framework Code First (七)空间数据类型 Spatial Data Types

    声明:本文针对 EF5+, Visual Studio 2012+ 空间数据类型(Spatial Data Types)是在 EF5 中引入的,空间数据类型表现有两种: Geography (地理学上 ...

随机推荐

  1. ES6-浏览器运行环境配置方法

    现在ES6用的越来越多,想要学习使用ES6,只需简单搭建引入几个js即可运行ES6代码 但是需要基本的服务器环境下运行(如http://10.12.8.161:8047/js-test/export/ ...

  2. python 获取本机ip地址的方法(Unix 平台)

    #!/usr/bin/python import socket import fcntl import struct def get_ip_address(ifname): s = socket.so ...

  3. LeetCode Longest Harmonious Subsequence

    原题链接在这里:https://leetcode.com/problems/longest-harmonious-subsequence/description/ 题目: We define a ha ...

  4. CH5E01[NOIP2010] 乌龟棋[暴力]

    众所周知,由于这个人太菜了,所以她又来切上古水题了. 显然最多$40^4$种状态,暴力跑出可以拼出多少种状态,然后按序号从小到大对应的状态瞎转移即可. 我知道我想繁了,但是不想改了,因为思路一出来,没 ...

  5. position:sticky属性测试

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  6. HDU1387:Team Queue

    浅谈队列:https://www.cnblogs.com/AKMer/p/10314965.html 题目传送门:http://acm.hdu.edu.cn/showproblem.php?pid=1 ...

  7. 10.Selenium+Python+任务计划程序实现定时发送邮件

    一.python具体代码实现 # coding=utf-8 import smtplib from email.mime.text import MIMEText from email.header ...

  8. 关于打包后提示无法连接到mongodb的情况

    昨天晚上要和前端联调. 打完jar包后发现无法连接到测试环境的数据库. 就很尴尬,最后发现问题在于mongodb的URI写错了: 正确的URI格式:mongodb://url:port/dbName ...

  9. 利用TaskScheduler处理Queue、Stack等类型的操作队列(生产者消费者场景)

    我们经常会遇到生产者消费者模式,比如前端各种UI操作事件触发后台逻辑等.在这种典型的应用场景中,我们可能会有4个业务处理逻辑(下文以P代表生产者,C代表消费者): 1. FIFO(先进先出)     ...

  10. maven打包指定main函数的入口,生成依赖的包

    为了使Jar包中指定Main方法位置和生成依赖包,需要在pom文件中加入如下配置: <build> <plugins> <plugin> <groupId&g ...