zoukankan      html  css  js  c++  java
  • EntityFrameworkCore自动迁移

    2019/05/14,EntityFrameworkCore 2.2.4

    有两种方式:

    使用Migrate()方法

    if (DbContext.Database.GetPendingMigrations().Any())
    {
        DbContext.Database.Migrate(); //执行迁移
    }
    

    Migrate()方法使用前需在程序包管理控制台执行Add-migration迁移命令。之后程序每次启动,GetPendingMigrations()都会去检测是否有待迁移内容,有的话,自动应用迁移。

    GetPendingMigrations方法官方文档说明
    Gets all migrations that are defined in the assembly but haven't been applied to the target database.

    使用EnsureCreated()方法

    //如果成功创建了数据库,则返回true
    DbContext.Database.EnsureCreated()
    

    此方法不需要先执行Add-migration迁移命令,如果数据库不存在,则自动创建并返回true
    如果已经创建了数据库后,又改动了实体Model和之前的库存在冲突,要注意删库让它自动重建,否则会报错。

    EnsureCreated方法官方文档说明
    Ensures that the database for the context exists. If it exists, no action is taken. If it does not exist then the database and all its schema are created. If the database exists, then no effort is made to ensure it is compatible with the model for this context.

  • 相关阅读:
    转载-MongoDB 分片集群技术
    EXT4参数优化及测试---转载
    9.16周记
    PHP优化思路
    2018.09.10-拾遗
    周记8
    落地成盒-发快递
    周记7
    GTX log 6
    Gitlab Jenkins WebHook 持续集成配置踩坑记
  • 原文地址:https://www.cnblogs.com/kasnti/p/10864668.html
Copyright © 2011-2022 走看看