code first , Migration

文章引用至: https://www.cnblogs.com/panchunting/p/entity-framework-code-first-migrations.html

随着业务的增加, 之前code first创建的表可能已经不能满足需求, 比如增加一个字段, 这样就出来了‘Migrations

 第一步:

  • 在 Package Manager Console 下运行命令 Enable-Migrations

需要熟悉的命令有:

  •  Add-Migration 将 scaffold 创建下一次基于上一次迁移以来的更改的迁移;
  • Update-Databse 将任何挂起的迁移应用到数据库

《1》: 新增字段: ‘Url’

1. console输入: Add-Migration AddNewUrl

2. 会看到产生一个新的cs文件

完善方法中的内容: (新增字段的类型需要自己定义, 如果为int型, 就是'c=>c.Int()')

 public partial class AddNewUrl : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.News", "Url", c => c.String());
        }
        
        public override void Down()
        {
            DropColumn("dbo.News", "Url");
        }
    }

 《2》 删除字段 

 1. console输入: Add-Migration DeleteNewUrl

 2. 对应产生文件,完善文件中的方法

public partial class DeleteNewUrl : DbMigration
    {
        public override void Up()
        {
            DropColumn("dbo.News", "Url");
        }
        
        public override void Down()
        {
        }
    }

3 执行更新 : Update-Database

《3》修改字段 类型

 1. console输入: Add-Migration UpdateRatingUrl

 2. 对应产生文件,完善文件中的方法

public partial class UpdateRatingUrl : DbMigration
    {
        public override void Up()
        {
            AlterColumn("dbo.News", "Rating", c => c.String());
        }
        
        public override void Down()
        {
        }
    }

3 执行更新 : Update-Database

《4》新增一个集合

 1. console输入: Add-Migration AddTagModel

 2. 对应产生文件,完善文件中的方法

public partial class AddTagModel : DbMigration
    {
        public override void Up()
        {
            CreateTable("dbo.Tags", c => new
            {
                TagId = c.Int(nullable: false, identity: true),
                TagName = c.String(maxLength: 500),
                NewId = c.Int(nullable: false)
            }).PrimaryKey(t => t.TagId)
            .ForeignKey("dbo.News", t => t.NewId, cascadeDelete: true)
            .Index(t => t.NewId)
            .Index(p => p.TagName, unique: true);
        }
        
        public override void Down()
        {
            DropIndex("dbo.Tags", new[] { "TagName" });
            DropForeignKey("dbo.Tags", "NewId", "dbo.News");
            DropIndex("dbo.Tags", new[] { "NewId" });
            DropTable("dbo.Tags");
        }
    }

3 执行更新 : Update-Database

4 执行结果

原文地址:https://www.cnblogs.com/zxhome/p/10343146.html