Automated Migration:

Entity framework 4.3 has introduced Automated Migration so that you don't have to process database migration manually in the code file, for each change you make in your domain classes. You just need to run a command in Package Manger Console to accomplish this.

Let's see how you can use the automated migration.

As you know, you don't have a database when you start writing your Code-First application. For example, we start writing an application with Student and Course entity classes. Before running the application, which does not have its database created yet, you have to enable automated migration by running the 'enable-migrations' command in Package Manager Console, as shown below:

First, open the package manager console from Tools → Library Package Manager → Package Manager Console and then run "enable-migrations –EnableAutomaticMigration:$true" command (make sure that the default project is the project where your context class is)

Once the command runs successfully, it creates an internal sealed Configuration class in the Migration folder in your project:

If you open this and see the class shown below, then you will find AutomaticMigrationsEnabled = true in the constructor.

internal sealed class Configuration : DbMigrationsConfiguration<SchoolDataLayer.SchoolDBContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
} protected override void Seed(SchoolDataLayer.SchoolDBContext context)
{
// This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}

You also need to set the database initializer in the context class with the new DB initialization strategy MigrateDatabaseToLatestVersion, as shown below:

public class SchoolDBContext: DbContext
{
public SchoolDBContext(): base("SchoolDBConnectionString")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<SchoolDBContext, SchoolDataLayer.Migrations.Configuration>("SchoolDBConnectionString")); } public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder)
{ base.OnModelCreating(modelBuilder);
} }

As you can see in the code shown above, we have passed the Configuration class name, which was created by command, along with the context class name.

Now you are set for automated migration. It will automatically take care of migration, when you change the model. Run the application and look at the created database:

You will find that it has created one system table __MigrationHistory along with other tables. This is where automated migration maintains the history of database changes.

Now let's add a Standard entity class. Run the application again and you will see that it has automatically created a Standard table.

Wait a minute, this works if you add a new entity class or remove an entity class, but what about adding or removing properties from the entity class? To try that, let's remove the Description property from Standard class and run the application.

Oops…. an error message will appear:

This is because you will lose data in description column, if you remove it from the Standard class. So to handle this kind of scenario, you have to set AutomaticMigrationDataLossAllowed = true in the configuration class constructor, along with AutomaticMigrationsEnabled = true.

Note: You can find more information about parameters that we can pass to the enable-migrations command using the "get-help enable-migrations" command. For more detailed help use "get-help enable-migrations –detailed"

Thus, migration can be handled automatically.

Entity Framework Code-First(21):Automated Migration的更多相关文章

  1. Entity Framework Tutorial Basics(21):CRUD Operation in Connected Scenario

    CRUD Operation in Connected Scenario: CRUD operation in connected scenario is a fairly easy task bec ...

  2. Entity Framework Code first(转载)

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

  3. Entity Framework Code First (三)Data Annotations

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

  4. Entity Framework Code First (二)Custom Conventions

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

  5. Entity Framework Code First (一)Conventions

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

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

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

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

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

  8. Entity Framework Code First (四)Fluent API - 配置属性/类型

    上篇博文说过当我们定义的类不能遵循约定(Conventions)的时候,Code First 提供了两种方式来配置你的类:DataAnnotations 和 Fluent API, 本文将关注 Flu ...

  9. Entity Framework Code First (八)迁移 Migrations

    创建初始模型和数据库 在开始使用迁移(Migrations)之前,我们需要一个 Project 和一个 Code First Model, 对于本文将使用典型的 Blog 和 Post 模型 创建一个 ...

随机推荐

  1. SQLAlchemyの增删改查

    用a*my写原味sql from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, I ...

  2. Uva1401(字典树)

    1401 - Remember the Word Time limit: 3.000 seconds Neal is very curious about combinatorial problems ...

  3. set/multiset和map/multimap用法小结

    二叉搜索树是ACM中经常需要用到的数据结构,熟练掌握map和set的用法很关键,现对其做一个简单的总结. 主要的功能有:插入元素,查找元素,删除,遍历/反向遍历. 插入,删除和查找操作的时间都和树的高 ...

  4. HihoCoder1139 二分·二分答案

    描述 在上一回和上上回里我们知道Nettle在玩<艦これ>,Nettle在整理好舰队之后终于准备出海捞船和敌军交战了.在这个游戏里面,海域是N个战略点(编号1..N)组成,如下图所示其中红 ...

  5. c#多线程实现定时执行代码与lock锁操作

    总结以下三种方法,实现c#每隔一段时间执行代码: 方法一:调用线程执行方法,在方法中实现死循环,每个循环Sleep设定时间: 方法二:使用System.Timers.Timer类: 方法三:使用Sys ...

  6. mysql5.6之 传输表空间迁移表或恢复误删除的表

    一,简单说明: 1),传输表空间的限制:  1,mysql 版本 5.6.6 及其以上,并且版本建议源和目标版本建议都是GA版并且大版本一样  2,表引擎为innodb并且开启独立表空间  innod ...

  7. POJ1020(小正方形铺大正方形)

    Anniversary Cake Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 16579   Accepted: 5403 ...

  8. Java基础--比较器Comparator

    Comparable接口和Comparator接口都是用来定义集合中的排序的,只是Comparable是在集合内部定义排序的实现,Comparator是在集合外部排序的实现. Comparable 的 ...

  9. MySQL 5.6 date 与 string 的转换和比较

    我们有张表,表中有一个字段 dpt_date ,SQL 类型为 date,表示离开日期. 我们将 dpt_date 与字符串 ‘2016-03-09’ 进行比较,发现效率低于 dpt_date 转换为 ...

  10. spring学习七

    一: web.xml中常用配置元素? <servlet></servlet>: 在向servlet或JSP页面制定初始化参数或定制URL时,首先命名servlet或JSP页面. ...