Code-based Migration:

Code-based migration is useful when you want more control on the migration, i.e. set default value of the column, etc.

Code-First has two commands for code based migration:

  1. Add-migration: It will scaffold the next migration for the changes you have made to your domain classes
  2. Update-database: It will apply pending changes to the database based on latest scaffolding code file you created using "Add-Migration" command

Assume that you have Student and Course entity classes initially and you want to use code-based migration for your application. Before running the commands above, you must enable migration for your application, by using the enable-migrations commands. These are in package manager that we used previously for automatic migration. This will create a configuration file, as was the case with automated migration. Also, you need to set the database initializer in the context class:

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);
} }

Now, you have to create a scaffold code file which consists of your database requirement from your existing domain classes. You can do this by running the “add-migration" command in the package manager. (from Tools → Library Package Manager → Package Manager Console). You will have to pass the name parameter, which will be part of the code file name.

Add-Migration command Syntax:

    Add-Migration [-Name] <String> [-Force]
[-ProjectName <String>] [-StartUpProjectName <String>]
[-ConfigurationTypeName <String>] [-ConnectionStringName <String>]
[-IgnoreChanges] [<CommonParameters>] Add-Migration [-Name] <String> [-Force]
[-ProjectName <String>] [-StartUpProjectName <String>]
[-ConfigurationTypeName <String>] -ConnectionString <String>
-ConnectionProviderName <String> [-IgnoreChanges] [<Common Parameters>]

You can see that this command has created a new file in the Migration folder with the name of the parameter you passed to the command with a timestamp prefix:

After creating the file above using the add-migration command, you have to update the database. You can create or update the database using the “update-database” command. You can use –verbose to see what's going on in the database:

Update-Database command syntax:

Update-Database [-SourceMigration <String>]
[-TargetMigration <String>] [-Script] [-Force] [-ProjectName <String>]
[-StartUpProjectName <String>] [-ConfigurationTypeName <String>]
[-ConnectionStringName <String>] [<CommonParameters>] Update-Database [-SourceMigration <String>] [-TargetMigration <String>]
[-Script] [-Force] [-ProjectName <String>] [-StartUpProjectName <String>]
[-ConfigurationTypeName <String>] -ConnectionString <String>
-ConnectionProviderName <String> [<CommonParameters>]

At this point, the database will be created or updated.

Now, suppose you added more domain classes. So before running the application, you have to create a scaffold file for new classes, by executing the "Add-Migration" command. Once it creates the file, update the database using the Update-Database command. In this way, you have to repeat the Add-Migration and Update-Database command each time you make any changes in your domain classes.

Rollback Database change:

Suppose you want to roll back the database schema to any of the previous states, then you can use "update-database" command with –TargetMigration parameter as shown below:

update-database -TargetMigration:"First School DB schema"

Use the "get-migration" command to see what migration has been applied.

Note: Use the "get-help" command for add-migration and update-database command in order to see what parameters can be passed with this command.

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

  1. Entity Framework Tutorial Basics(22):Disconnected Entities

    Disconnected Entities: Before we see how to perform CRUD operation on disconnected entity graph, let ...

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

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

  3. Entity Framework Tutorial Basics(37):Lazy Loading

    Lazy Loading: One of the important functions of Entity Framework is lazy loading. Lazy loading means ...

  4. Entity Framework Tutorial Basics(36):Eager Loading

    Eager Loading: Eager loading is the process whereby a query for one type of entity also loads relate ...

  5. Entity Framework Tutorial Basics(32):Enum Support

    Enum in Entity Framework: You can now have an Enum in Entity Framework 5.0 onwards. EF 5 should targ ...

  6. Entity Framework Tutorial Basics(29):Stored Procedure in Entity Framework

    Stored Procedure in Entity Framework: Entity Framework has the ability to automatically build native ...

  7. Entity Framework Tutorial Basics(28):Concurrency

    Concurrency in Entity Framework: Entity Framework supports Optimistic Concurrency by default. In the ...

  8. Entity Framework Tutorial Basics(27):Update Entity Graph

    Update Entity Graph using DbContext: Updating an entity graph in disconnected scenario is a complex ...

  9. Entity Framework Tutorial Basics(19):Change Tracking

    Change Tracking in Entity Framework: Here, you will learn how entity framework tracks changes on ent ...

  10. Entity Framework Tutorial Basics(15):Querying with EDM

    Querying with EDM: We have created EDM, DbContext, and entity classes in the previous sections. Here ...

随机推荐

  1. 使用Visio画UML模型

    Microsoft Office Visio“UML 模型图” 模板为创建复杂软件系统的面向对象的模型 (模型:建模系统的一种抽象表示,它从特定的视角并在某一抽象级别上指定建模系统.) 提供全面的支持 ...

  2. eclipse 环境 JUnit 测试框架(junit.framework.* 与 org.junit.*)

    如下所示,先通过 build path 导入 junit 环境依赖的 jar 包: 1. junit.framework.* junit.framework.* 主要类和函数: Test TestCa ...

  3. C8051F340 USB Fn hacking

    /************************************************************************************ * C8051F340 US ...

  4. OpenCV - opencv3 图像处理 之 图像缩放( python与c++实现 )

    转自:https://www.cnblogs.com/dyufei/p/8205121.html 一. 主要函数介绍 1) 图像大小变换 cvResize () 原型: voidcvResize(co ...

  5. 作业派NABCD的特点分析

    Need:根据我们用户的调查,我们发现用户希望在作业派获取一些课本上的答案等类似的东西,以方便及时解决课本的问题. Approach:但是仅仅靠管理员来上传文件时园不能解决用户的问题.所以我们想让我们 ...

  6. 排列(加了点小set就过了,哈哈哈)

    Ray又对数字的列产生了兴趣: 现有四张卡片,用这四张卡片能排列出很多不同的4位数,要求按从小到大的顺序输出这些4位数. 输入描述: 1 2 3 4 1 1 2 3 0 1 2 3 0 0 0 0输出 ...

  7. angular : copy vs extend

    While using AngularJS, we come across some situation in which we need to copy one object to another ...

  8. Poj 2421 Constructing Roads(Prim 最小生成树)

    题意:有几个村庄,要修最短的路,使得这几个村庄连通.但是现在已经有了几条路,求在已有路径上还要修至少多长的路. 分析:用Prim求最小生成树,将已有路径的长度置为0,由于0是最小的长度,所以一定会被P ...

  9. MyBatis定制SQL集中特殊的处理方式

    举例说明: 1.查询 姓为林的数据  LIKE 3种 Select * from sys_user where user_name like '林%' 关于结果集合多个参数传递数据 特殊字符的处理

  10. 蓝桥杯 基础练习 BASIC-14 时间转换

    基础练习 时间转换   时间限制:1.0s   内存限制:512.0MB 问题描述 给定一个以秒为单位的时间t,要求用“<H>:<M>:<S>”的格式来表示这个时间 ...