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. SVN的安装和使用

    1.安装 下载SVN,一直默认安装 安装成功后,配置环境变量path=C:\Program Files\TortoiseSVN\bin 验证SVN安装是否成功:adb -help 或 adb -ver ...

  2. HDU - 5126 stars (CDQ分治)

    题目链接 题目大意:一共有Q(1<=Q<=50000)组操作,操作分为两种: 1.在x,y,z处添加一颗星星 2.询问以(x1,y1,z1)与(x2,y2,z2)为左上和右下顶点的矩形之间 ...

  3. myeclipse2014中如何安装freeMarker插件(支持ftl语法高亮)

    MyEcplise2014安装Freemarker插件(支持.ftl文件) 1.下载插件:http://sourceforge.net/projects/freemarker-ide/?source= ...

  4. storm 学习教程

    转自:http://blog.csdn.net/hrn1216/article/details/51538962 翻译太累了,再也不想去翻译了,真的太累了: 在这个教程中, 你将学到如何创建一个Sto ...

  5. swing之borderlayout

    import java.awt.BorderLayout; import javax.swing.JButton; import javax.swing.JFrame; //1.继承 JFrame类 ...

  6. SQL Server 学习系列之六

    SQL Server 学习系列之六 SQL Server 学习系列之一(薪酬方案+基础) SQL Server 学习系列之二(日期格式问题) SQL Server 学习系列之三(SQL 关键字) SQ ...

  7. 基于 WebSocket 的 MQTT 移动推送方案

    WebSphere MQ Telemetry Transport 简介 WebSphere MQ Telemetry Transport (MQTT) 是一项异步消息传输协议,是 IBM 在分析了他们 ...

  8. laravel 添加自定义类 全局自定义方法 自定义常量

    添加自定义类 https://blog.csdn.net/suchfool/article/details/38758367 https://blog.csdn.net/liukai6/article ...

  9. SqlServer 用户和权限操作

    use [master] GO --创建用户,Test,密码Test CREATE LOGIN [TestUser] WITH PASSWORD=N'Test', DEFAULT_DATABASE=[ ...

  10. 蓝桥杯 算法训练 ALGO-147 4-3水仙花数

    算法训练 4-3水仙花数   时间限制:1.0s   内存限制:256.0MB 问题描述 打印所有100至999之间的水仙花数.所谓水仙花数是指满足其各位数字立方和为该数字本身的整数,例如 153=1 ...