• 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 执行结果

  • 相关阅读:
    Python-炫酷二维码
    Dictionary 序列化与反序列化
    获取数据库所有表名与字段名
    LinQ To Object 基本用法
    使用jq操作脚本生成元素的事件
    表单验证如何让select设置为必选
    js实现复制功能兼容ios
    微信小程序使用函数防抖解决重复点击消耗性能问题
    electronr进行签名与公证
    使用electron在mac升级签名后进行升级出现“QRLUpdaterErrorDomain”的错误
  • 原文地址:https://www.cnblogs.com/zxhome/p/10343146.html
Copyright © 2020-2023  润新知