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 build
,dotnet 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