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. c++ 修改stl set中的元素

    set的迭代器it有const修饰符,那么对它元素的修改就必然不能成功了.但是有时候遇到要修改stl set元素的问题,这个问题一般的解决方法是先erase这个元素,然后再insert,这样效率很低, ...

  2. 转载:maven依赖范围

    其中依赖范围scope 用来控制依赖和编译,测试,运行的classpath(注意是与classpath)的关系. 主要的是三种依赖关系如下:1.compile: 默认编译依赖范围.对于编译,测试,运行 ...

  3. 大整数乘法(Comba 乘法 (Comba  Multiplication)原理)

    Comba 乘法以(在密码学方面)不太出名的 Paul G. Comba 得名.上面的笔算乘法,虽然比较简单, 但是有个很大的问题:在 O(n^2) 的复杂度上进行计算和向上传递进位,看看前面的那个竖 ...

  4. ftp上传下载 java FTPClient (zhuan)

    项目需要,网上搜了搜,很多,但问题也不少,估计转来转去,少了不少东西,而且也情况也不太一样.没办法,只能自己去写一个. 一,    安装sserv-u ftp服务器 版本10.1.0.1 我所设服务器 ...

  5. BZOJ4303:数列

    浅谈\(K-D\) \(Tree\):https://www.cnblogs.com/AKMer/p/10387266.html 题目传送门:https://lydsy.com/JudgeOnline ...

  6. 使用批处理自动发布IIS站点,基于IIS7及以上

    经过研究,终于使用批处理解决了站点发布步骤多的问题. 完整批处理如下: @set "sitePath=%~dp0" @echo 新建程序池 @C:\Windows\System32 ...

  7. Unix文件指令-Mac终端命令应用

    pwd:查看当前文件夹 cd: 打开文件夹 ls:列出当前路径下所有文件 ls -l :列出当前路径下的所有文件详细信息. mkdir: 新建文件夹 touch: 创建文件   eg: touch t ...

  8. MSDN 学习网站

    -MSDN中文网站http://msdn.microsoft.com/zh-cn/-MSDN Webcast 中文网络广播http://msdn.microsoft.com/zh-cn/dd79616 ...

  9. Zookeeper学习(八):Zookeeper的数据发布与订阅模式

     http://blog.csdn.net/ZuoAnYinXiang/article/category/6104448 1.发布订阅的基本概念        1.发布订阅模式可以看成一对多的关系:多 ...

  10. 2016.2.28 DataTable用法汇总

    将控件的DataSource转换为DataTable,但是,此控件的DataSource绑定时必须是DataTable,不能是List DataTable dt = (bgvRoutePortion. ...