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. url字符串中含中文的转码方法

    凡是用get方法的,url里含中文的,都需要调用上面的函数进行编码.要不然会被当成二进制截断. //URL编码 +(NSString*)urlEncode:(NSString *)str { int  ...

  2. OpenCV-Python在图片上输出中文

    OpenCV中在图片上输出中文一般需要借助FreeType库实现.FreeType库是一个完全免费(开源)的.高质量的且可移植的字体引擎,它提供统一的接口来访问多种字体格式文件.但使用FreeType ...

  3. java 实现拖动文件到窗口功能

    package tuo; import java.awt.BorderLayout; import java.awt.Color; import java.awt.datatransfer.DataF ...

  4. rabbitmq的vhost与用户管理

    当我们在创建用户时,会指定用户能访问一个虚拟机,并且该用户只能访问该虚拟机下的队列和交换机,如果没有指定,默认的是”/”;一个rabbitmq服务器上可以运行多个vhost,以便于适用不同的业务需要, ...

  5. vue.js初学(一) vue的入门编程

    1:首先引入vue.js 2:点击事件 <div id='clickVue'> <p>{{message}}</p> <button v-on:click=& ...

  6. Makefile生成

    安装:sudo yum install automake使用: 1 运行autoscan生成两个文件:autoscan.log和configure.scan.将configure.scan重命名为co ...

  7. bash 中的行处理命令 awk

    转自:http://blog.chinaunix.net/uid-23302288-id-3785105.html

  8. Day2-VIM(四):修改

    字符替换 r 单个字符替换 R 连续替换 - 更改大小写 很简单,多试试就行了 tips:4-更改连续4个字符的大小写,很有意思 单词修改 cw 从光标处修改到单词结尾 cb 从光标处修改到单词开头 ...

  9. windows任务管理器中的工作设置内存,内存专用工作集,提交大小详解

    虽然是中文字,但是理解起来还是很困难,什么叫工作设置内存,什么叫内存专用工作集,什么叫提交大小,区别是什么,让人看了一头雾水. 通俗的讲工作设置内存是程序占用的物理内存(包含与其他程序共享的一部分), ...

  10. 浅谈NB_LOT和LTE CAT M1

    1.什么是NB-IoT? 窄带物联网(NB-IoT)也被称为LTE Cat NB1也是一种低功耗广域(LPWA,Low Power Wide Area)技术,它已经开发出来,可以使用现有的移动网络将各 ...