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. RedHat5.8 编译内核驱动 合成initrd.img

    /******************************************************************* * RedHat5.8 编译内核驱动 合成initrd.img ...

  2. linux下的制作静态库并使用它

    静态库所要用的源文件 文件 fred.c   #include <stdio.h>   void fred(int argc) {     printf("void fred(i ...

  3. LeetCode Maximum Distance in Arrays

    原题链接在这里:https://leetcode.com/problems/maximum-distance-in-arrays/description/ 题目: Given m arrays, an ...

  4. python函数-filter()

    filter(func, seq)  filter()函数是 Python 内置的另一个有用的高阶函数,filter()函数接收一个函数 f 和一个list,这个函数 f 的作用是对每个元素进行判断, ...

  5. JSF拦截ajax请求并传递参数方法

    我们可以利用f:ajax做一些简单的ajax操作,但是遇到复杂的逻辑,它不能简单的去实现,jsf提供了一种方法,可以调用它内部的js方法去实现复杂的逻辑. 首先要在页面引入jsf的js文件: < ...

  6. hihoCoder#1068(RMQ-ST算法)

    时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 小Hi和小Ho在美国旅行了相当长的一段时间之后,终于准备要回国啦!而在回国之前,他们准备去超市采购一些当地特产——比如汉堡 ...

  7. oralce 记一次 External Procedure initial connection 处理

    1 环境 oracle 11.2.0.4 RAC(2 nodes),centos 6.8,实体机 2 问题 线上环境执行一条sql sql> select ST_AsText(ST_Geomet ...

  8. git学习4 常用命令

    1:更新: 更新后,更新只在Workspace中,没有到暂存区.git status可以查看当前状态. git add <file>  可以放到待提交区.      git  checko ...

  9. [iOS]UIImageView增加圆角

    [iOS]UIImageView增加圆角 "如何给一个UIImageView增加圆角?有几种方法?各自区别?" 备注:本文参考自http://www.jianshu.com/p/d ...

  10. ARRINC424—MORA(GRID)格式

    每一整数经.纬度为一格,每格MORA值3位数字,表示百英尺.无法获知MORA值得网格一UNK表示. 经纬网格起始点坐标,每个网格从左下角开始计数,每经纬度一度切分一个网格.每行数据代表某一维度上往东或 ...