EntityFrameworkCore使用Migrations自动更新数据库

系统环境:Win10

IDE:VS2017 RC4

.netcore版本:1.1

一、新建ASP.NET Core WebApi项目

二、引用Microsoft.EntityFrameworkCore.Sqlite

使用VS Nuget工具,添加对Microsoft.EntityFrameworkCore.Sqlite库的引用,如使用其他数据库,添加相对应的引用即可。

三、使项目支持dotnet ef工具以使用Migrations

手动修改项目csproj文件

ItemGroup.DotNetCliToolReference节点添加Microsoft.EntityFrameworkCore.Tools.DotNet工具的引用,注意版本1.0.0-msbuild3-final,VS2017 RC4 用的是MSBuild格式。

并在ItemGroup.PackageReference节点添加对Microsoft.EntityFrameworkCore.Design的引用,因为使用dotnet ef migrations add命令需要该引用。

  <ItemGroup>
······
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.0" />
······
</ItemGroup>
<ItemGroup>
······
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0-msbuild3-final" />
</ItemGroup>

手动添加的原因是我在Nuget添加Microsoft.EntityFrameworkCore.Tools.DotNet时,报了一个错,可能是VS2017 RC版本的BUG:

Package 'Microsoft.EntityFrameworkCore.Tools.DotNet 1.1.0-preview4-final' has a package type 'DotnetCliTool' that is not supported by project 'EntityFrameworkCoreMigrationsDemo'.

CMD命令行cd到项目目录下(非Solution目录),执行dotnet builddotnet ef

C:\WorkSpacesC\DotNetCore\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo>dotnet build
Microsoft (R) Build Engine version 15.1.545.13942
Copyright (C) Microsoft Corporation. All rights reserved. Startup.cs(45,13): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. [C:\WorkSpacesC\DotNetCore\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo.csproj]
EntityFrameworkCoreMigrationsDemo -> C:\WorkSpacesC\DotNetCore\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo\bin\Debug\netcoreapp1.0\EntityFrameworkCoreMigrationsDemo.dll Build succeeded. Startup.cs(45,13): warning CS4014: Because this call is not awaited, execution of the current method continues before the call is completed. Consider applying the 'await' operator to the result of the call. [C:\WorkSpacesC\DotNetCore\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo.csproj]
1 Warning(s)
0 Error(s) Time Elapsed 00:00:04.76 C:\WorkSpacesC\DotNetCore\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo>dotnet ef _/\__
---==/ \\
___ ___ |. \|\
| __|| __| | ) \\\
| _| | _| \_/ | //|\\
|___||_| / \\\/\\ Entity Framework Core .NET Command Line Tools 1.0.0-msbuild3-final Usage: dotnet ef [options] [command] Options:
--version Show version information
-h|--help Show help information
-v|--verbose Show verbose output.
--no-color Don't colorize output.
--prefix-output Prefix output with level. Commands:
database Commands to manage the database.
dbcontext Commands to manage DbContext types.
migrations Commands to manage migrations. Use "dotnet ef [command] --help" for more information about a command.

可以看到EF独角兽,说明工具引用成功。

四、创建实例DbContext

新建DbContext以及相关Models

using Microsoft.EntityFrameworkCore;
using System.Collections.Generic; namespace EntityFrameworkCoreMigrationsDemo.Data
{
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Filename=./Blogging.db");
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } public List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; } public int BlogId { get; set; }
public Blog Blog { get; set; }
}
}

在Startup将DbContext注册为服务

namespace EntityFrameworkCoreMigrationsDemo
{
public class Startup
{
······
public void ConfigureServices(IServiceCollection services)
{
······
services.AddDbContext<BloggingContext>();
}
······
}
}

五、使用Migrations

新建数据库初始化类InitializeAsync.cs

using Microsoft.EntityFrameworkCore;
using System.Threading.Tasks; namespace EntityFrameworkCoreMigrationsDemo.Data
{
public class DbInitializer
{
public async Task InitializeAsync(BloggingContext context)
{
//var migrations = await context.Database.GetPendingMigrationsAsync();//获取未应用的Migrations,不必要,MigrateAsync方法会自动处理
await context.Database.MigrateAsync();//根据Migrations修改/创建数据库
}
}
}

在Startup.cs的Configure方法中,添加参数BloggingContext context,netcore会使用DI将DbContext注入到Configure方法,并添加对DbInitializer的调用。

    public class Startup
{
······
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, BloggingContext context)
{
······
new DbInitializer().InitializeAsync(context);
}
}

使用dotnet ef命令创建Migrations:dotnet ef migrations add [NAME]

C:\WorkSpacesC\DotNetCore\EntityFrameworkCoreMigrationsDemo\EntityFrameworkCoreMigrationsDemo>dotnet ef migrations add Initial

Build succeeded.
0 Warning(s)
0 Error(s) Time Elapsed 00:00:02.32
Done. To undo this action, use 'ef migrations remove'

执行成功后,可以看到项目目录下多了个文件夹Migrations,里面就是自动生成的Migrations文件。

创建更新Migrations的命令跟创建初始的一样,只是最后一个参数自己定义即可。

最后执行代码,成功创建了新的数据库,并且里面有一个表__EFMigrationsHistory,是自动生成的用来记录Migrations记录。

修改Blog类,添加一个字段public string NewField { get; set; },在命令行执行命令dotnet ef migrations add NewField,然后运行程序,可以看到数据库已经更新,__EFMigrationsHistory表也多了一条对应的记录。

其他说明

因为我习惯使用VS,但是构建这个项目的过程中,需要使用到命令行,还需要手动修改csproj文件,所以这篇文章的操作过程有可能点乱,我自己在写Demo的时候,也是多次重启VS使VS能够加载最新的项目。

Demo源码,测试通过:Github

参考:

.NET Core - New Database Create your model

Walkthrough: Entity Framework Core 1.1 with Migrations

EntityFrameworkCore使用Migrations自动更新数据库的更多相关文章

  1. Code First 下自动更新数据库结构(Automatic Migrations)

    示例 Web.config <?xml version="1.0" encoding="utf-8"?> <configuration> ...

  2. EF修改model自动更新数据库

    最近用MVC+EF学习时遇到修改model后而数据库没更新报错,就在网上找关于数据迁移自动更新数据库的,折腾了大半天终于弄了出来 第一步:在程序包管理器控制台里: Enable-Migrations ...

  3. day35-hibernate映射 03-Hibernate持久态对象自动更新数据库

    持久态对象一个非常重要的能力:自动更新数据库. package cn.itcast.hibernate3.demo1; import static org.junit.Assert.*; import ...

  4. EF-使用迁移技术让程序自动更新数据库表结构

    承接上一篇文章:关于类库中EntityFramework之CodeFirst(代码优先)的操作浅析 本篇讲述的是怎么使用迁移技术让程序自动通过ORM框架将模型实体类结构映射到现有数据库,并新增或修改与 ...

  5. MVC Code First 当实体类发生变化时,如何自动更新数据库表

    下面做一个例子,Category是用户新建的一个实体类,然后添加一个字段,然后让数据库中的Category表也添加一个字段 1.Category.cs

  6. 解决SpringBoot+JPA中使用set方法时自动更新数据库问题

    项目进行了三分之二了,突然出现一个很诡异的bug,数据库存储的用户表中密码信息总是自动消失一部分,头疼了几天后突然想起同事有个对低权限用户查询的用户信息向前台传送时会把密码设成null后再传输,心想是 ...

  7. 设置EntityFramework 在开发时自动更新数据库

    1. NuGet 下载EntityFramework. 2. 定义Context 和 打开NuGet 命令 执行 Enable-Migrations , Libaray.DAL.Migrations. ...

  8. 第八篇 elasticsearch链接mysql自动更新数据库

    增量更新 input { jdbc { jdbc_driver_library => "D:\tools\mysql\mysql-connector-java-5.1.45/mysql ...

  9. vs2013, EF6.0.0.0 使用Migrations来更新数据库时报错

    1.vs中,程序包管理器控制台 2.执行,Enable-Migrations 报错: Migrations have already been enabled in project 'dd'. To ...

随机推荐

  1. 纠错输出编码法ECOC

    纠错输出编码法(Error-Correcting Output Codes,ECOC)不仅能够将多类分类问题转化为多个两类问题,而且利用纠错输出码本身具有纠错能力的特性,可以提高监督学习算法的预测精度 ...

  2. 字符集 ISO-8859-1(2)

    HTML 支持的数学符号 结果 描述 实体名称 实体编号 ∀ for all ∀ ∀ ∂ part ∂ ∂ ∃ exists &exists; ∃ ∅ empty ∅ ∅ ∇ nabla ∇ ...

  3. C# is 运算符

    is 运算符并不是说明对象是某种类型的一种方式,而是可以检查对象是否是给定的类型,或者是否可以转换为给定的类型,如果是,这个运算符就返回true.is 运算符的语法如下: <operand> ...

  4. Java div 使用说明

    1. 置于底部 position:absolute; bottom:0;

  5. onfocus在火狐、ie10浏览器失效解决方法方法

    <script>      function setit(){      if(document.all){      document.getElementById("myfr ...

  6. 大咖,我能转行做UX设计师吗?

    前几天,有个朋友找到我,叫我给分析下他适不适合转UX设计.他的专业是建筑设计,之所以要辞职,也就是公司破事多,老板又不看重他.看到UX设计这个行业的前景很不错,想要转行.他说的也没错, 现在的UX设计 ...

  7. linux上静态库链接的有关问题

    求大神,linux下静态库链接的问题有两个文件和一个库,a.c, b.c,libh.a,其中b.c里面会有调用libh.a的函数func1,现在将a.c, b.c,libh.a编译链接生成可执行文件, ...

  8. Nginx反向代理、CORS、JSONP等跨域请求解决方法总结

    由于 Javascript 同源策略的存在使得一个源中加载来自其它源中资源的行为受到了限制.即会出现跨域请求禁止. 通俗一点说就是如果存在协议.域名.端口或者子域名不同服务端,或一者为IP地址,一者为 ...

  9. C++ Primer 笔记 第一章

    C++ Primer 学习笔记 第一章 快速入门 1.1 main函数 系统通过调用main函数来执行程序,并通过main函数的返回值确定程序是否成功执行完毕.通常返回0值表明程序成功执行完毕: ma ...

  10. 理解Window和WindowManager

    Window表示一个窗口的概念,Window是一个抽象类,它的具体实现是PhoneWindow.创建一个Window,需要通过WindowManager即可完成,WindowManager是外界访问W ...