ASP.NET Core Identity 迁移数据 - ASP.NET Core 基础教程 - 简单教程,简单编程
原文:ASP.NET Core Identity 遷移數(shù)據(jù) - ASP.NET Core 基礎(chǔ)教程 - 簡單教程,簡單編程
ASP.NET Core Identity 遷移數(shù)據(jù)
上一章節(jié)中我們配置了 Identity ,也讓我們的應(yīng)用程序正常運(yùn)行起來了,在訪問未授權(quán)頁面的時(shí)候會(huì)跳轉(zhuǎn)到 /Accout/Login 頁面。接下來我們就要實(shí)現(xiàn)登錄的功能
但是,咦,好像還沒創(chuàng)建用戶表呢..哎呀,不是沒創(chuàng)建用戶表,而是沒做 Identity 的數(shù)據(jù)遷移
那么,本章節(jié)接下來的內(nèi)容,就開始遷移 Identity 數(shù)據(jù)唄
數(shù)據(jù)庫連接配置
對(duì)了,我在看官方文檔的過程中,發(fā)現(xiàn)了兩種配置數(shù)據(jù)庫連接的方法
一、第一種是在 Startup 類中的 ConfigureServices 方法中配置
services.AddEntityFrameworkSqlite().AddDbContext<HelloWorldDBContext>(options => options.UseSqlite(Configuration["database:connection"]));這種方法需要我們的 HelloWorldDBContext 有一個(gè)可以接受 DbContextOptions<HelloWorldDBContext> 類型參數(shù)的構(gòu)造函數(shù)
public HelloWorldDBContext(DbContextOptions<HelloWorldDBContext> options): base(options) { }二、第二種方法只需要在 HelloWorldDBContext 類中重寫方法 OnConfiguring
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlite("Data Source=blogging.db"); }然后在 Startup 類中的 ConfigureServices 方法種就可以這么寫了
services.AddEntityFrameworkSqlite().AddDbContext<HelloWorldDBContext>();看起來是不是第二種更簡單更方便更簡潔
后知后覺,醉了,這次,我們就使用這種方法吧,然后將其它相關(guān)的都統(tǒng)統(tǒng)刪掉
首先刪除 Startup 類中的 ConfigureServices 方法中的相關(guān)配置
public void ConfigureServices(IServiceCollection services) {services.AddMvc();services.AddEntityFrameworkSqlite().AddDbContext<HelloWorldDBContext>();services.AddIdentity<User, IdentityRole>().AddEntityFrameworkStores<HelloWorldDBContext>();}其次在 HelloWorldDBContext 類中重寫方法 OnConfiguring,且刪除帶參數(shù)的構(gòu)造函數(shù)
其實(shí)刪除了帶參數(shù)的構(gòu)造函數(shù),那么不帶參數(shù)的構(gòu)造函數(shù)也可以刪除了,于是就變成了
using System; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.Extensions.Configuration;namespace HelloWorld.Models {public class HelloWorldDBContext:IdentityDbContext<User>{public DbSet<Employee> Employees { get; set; }protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder){optionsBuilder.UseSqlite("Data Source=blogging.db");}} }這種方法我還沒找到如何引用 Configuration 屬性的方式,如果你知道,請(qǐng)麻煩告訴我下
重啟下我們的應(yīng)用程序,刷新下首頁,看看是否正常輸出
最佳實(shí)戰(zhàn)
實(shí)際應(yīng)用中,你千萬不要像我這么激進(jìn),因?yàn)檫@兩種方式是互補(bǔ)的關(guān)系,也就是說 OnConfiguring() 方法可以覆寫傳遞給 HelloWorldDBContext(DbContextOptions<HelloWorldDBContext> options) 的連接
當(dāng)一個(gè)應(yīng)用需要連接多個(gè)數(shù)據(jù)庫的時(shí)候,結(jié)合這兩種方式非常有用,第一種方式用于默認(rèn)的數(shù)據(jù)庫,第二種方式用于特定的數(shù)據(jù)庫
遷移 Identity 數(shù)據(jù)
好了,讓我門言歸正傳吧,開始遷移 Identity 數(shù)據(jù)。其實(shí)前面的 EF 框架中我們已經(jīng)遷移過一次了,不知道大家是否還記得如何遷移呢
首先停止我們的應(yīng)用程序,不然會(huì)報(bào)錯(cuò),因?yàn)槲覀兪褂玫氖俏募到y(tǒng)數(shù)據(jù)庫
其次打開 控制臺(tái)窗口 ( 終端或 Power Shell 或 命令提示符 ),定位到我們的 HelloWorld 項(xiàng)目下
$ cd ~/Developer/aspnetcore/HelloWorld/HelloWorld我用的是 macOS,且我的 HelloWorld 保存在 ~/Developer/aspnetcore/HelloWorld/HelloWorld
然后使用 ls 命名就可以列出當(dāng)前目錄下的所有文件和子目錄
$ ls AppSettings.json Controllers HelloWorld.csproj Models Program.cs Properties Startup.cs Views bin obj wwwroot如果你使用的是 Windows,且使用的不是 Power Shell,那么你應(yīng)該使用 dir 命令而不是 ls 命令
如果能看到 HelloWorld.csproj 則說明處于正確的目錄,否則你應(yīng)該繼續(xù) cd 到該目錄下
然后可以運(yùn)行下列命令創(chuàng)建遷移代碼
dotnet ef migrations add InitialIdentity -v| dotnet | 是 .NET 框架所有命令的開始標(biāo)識(shí) |
| ef | 是指使用 Entity Framework 提供的命令 |
| migrations | 是指使用遷移命令 |
| add | 是指添加遷移 |
| InitialCreate | 是本次遷移的說明,你可以改成任意文本,但我們推薦最好是能清楚的描述本次遷移的意圖 |
| -v | 參數(shù)用于輸出創(chuàng)建遷移代碼時(shí)的運(yùn)行日志,方便出錯(cuò)時(shí)我們可以查看錯(cuò)在哪里 |
運(yùn)行結(jié)果如下
$ dotnet ef migrations add InitialIdentity -v Using project '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj'. Using startup project '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj'. Writing '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/obj/HelloWorld.csproj.EntityFrameworkCore.targets'... dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/var/folders/yk/2446sljj6hn82nvzkdgxltmw0000gn/T/tmpbjHVNk.tmp /verbosity:quiet /nologo /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj Writing '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/obj/HelloWorld.csproj.EntityFrameworkCore.targets'... dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/var/folders/yk/2446sljj6hn82nvzkdgxltmw0000gn/T/tmpDgtTNf.tmp /verbosity:quiet /nologo /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj dotnet build /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj /verbosity:quiet /nologo Build succeeded. 0 Warning(s) 0 Error(s) Time Elapsed 00:00:03.64 dotnet exec --depsfile /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.deps.json --additionalprobingpath /Users/yufei/.nuget/packages --additionalprobingpath /usr/local/share/dotnet/sdk/NuGetFallbackFolder --runtimeconfig /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.runtimeconfig.json /usr/local/share/dotnet/sdk/2.1.301/DotnetTools/dotnet-ef/2.1.1/tools/netcoreapp2.1/any/tools/netcoreapp2.0/any/ef.dll migrations add InitialIdentity --assembly /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.dll --startup-assembly /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.dll --project-dir /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/ --language C# --working-dir /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld --verbose --root-namespace HelloWorld Using assembly 'HelloWorld'. Using startup assembly 'HelloWorld'. Using application base '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1'. Using working directory '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld'. Using root namespace 'HelloWorld'. Using project directory '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/'. Finding DbContext classes... Finding IDesignTimeDbContextFactory implementations... Finding application service provider... Finding IWebHost accessor... Using environment 'Development'. Using application service provider from IWebHost accessor on 'Program'. Found DbContext 'HelloWorldDBContext'. Finding DbContext classes in the project... Using context 'HelloWorldDBContext'. Finding design-time services for provider 'Microsoft.EntityFrameworkCore.Sqlite'... Using design-time services from provider 'Microsoft.EntityFrameworkCore.Sqlite'. Finding design-time services referenced by assembly 'HelloWorld'. No referenced design-time services were found. Finding IDesignTimeServices implementations in assembly 'HelloWorld'... No design-time services were found. DetectChanges starting for 'HelloWorldDBContext'. DetectChanges completed for 'HelloWorldDBContext'. DetectChanges starting for 'HelloWorldDBContext'. DetectChanges completed for 'HelloWorldDBContext'. DetectChanges starting for 'HelloWorldDBContext'. DetectChanges completed for 'HelloWorldDBContext'. DetectChanges starting for 'HelloWorldDBContext'. DetectChanges completed for 'HelloWorldDBContext'. Writing migration to '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/Migrations/20180624040354_InitialIdentity.cs'. Writing model snapshot to '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/Migrations/HelloWorldDBContextModelSnapshot.cs'. 'HelloWorldDBContext' disposed. Done. To undo this action, use 'ef migrations remove'大概意思就是經(jīng)過漫長的歲月,成功創(chuàng)建了遷移代碼
這一步非常容易出錯(cuò),如果你有任何錯(cuò)誤,歡迎你在討論區(qū)留下你包括的意見
ASP.NET Core 討論區(qū)
創(chuàng)建遷移成功后,我們就可以使用下面的命令查看當(dāng)前有多少遷移代碼和它們的狀態(tài)
$ dotnet ef migrations list運(yùn)行結(jié)果如下
$ dotnet ef migrations list 20180623011249_InitialCreate 20180624040354_InitialIdentity可以看到總共有兩個(gè)遷移代碼,下面那個(gè) 20180624040354_InitialIdentity 就是我們剛剛創(chuàng)建
在解決方案管理器中我們還可以看到 Migrations 又多了很多文件
接下來我們就要開始應(yīng)用這些遷移來更新數(shù)據(jù)庫,執(zhí)行下面的命令來應(yīng)用遷移代碼
$ dotnet ef database update -v| dotnet | 是 .NET 框架所有命令的開始標(biāo)識(shí) |
| ef | 是指使用 Entity Framework 提供的命令 |
| database | 是指使用數(shù)據(jù)庫相關(guān)命令 |
| update | 是指更新數(shù)據(jù)庫 |
| -v | 參數(shù)用于輸出創(chuàng)建遷移代碼時(shí)的運(yùn)行日志,方便出錯(cuò)時(shí)我們可以查看錯(cuò)在哪里 |
執(zhí)行以上命令,輸出結(jié)果如下
$ dotnet ef database update -v Using project '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj'. Using startup project '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj'. Writing '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/obj/HelloWorld.csproj.EntityFrameworkCore.targets'... dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/var/folders/yk/2446sljj6hn82nvzkdgxltmw0000gn/T/tmp6jVQsB.tmp /verbosity:quiet /nologo /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj Writing '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/obj/HelloWorld.csproj.EntityFrameworkCore.targets'... dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/var/folders/yk/2446sljj6hn82nvzkdgxltmw0000gn/T/tmpXNRfCA.tmp /verbosity:quiet /nologo /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj dotnet build /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/HelloWorld.csproj /verbosity:quiet /nologo Build succeeded. 0 Warning(s) 0 Error(s) Time Elapsed 00:00:04.59 dotnet exec --depsfile /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.deps.json --additionalprobingpath /Users/yufei/.nuget/packages --additionalprobingpath /usr/local/share/dotnet/sdk/NuGetFallbackFolder --runtimeconfig /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.runtimeconfig.json /usr/local/share/dotnet/sdk/2.1.301/DotnetTools/dotnet-ef/2.1.1/tools/netcoreapp2.1/any/tools/netcoreapp2.0/any/ef.dll database update --assembly /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.dll --startup-assembly /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1/HelloWorld.dll --project-dir /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/ --language C# --working-dir /Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld --verbose --root-namespace HelloWorld Using assembly 'HelloWorld'. Using startup assembly 'HelloWorld'. Using application base '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/bin/Debug/netcoreapp2.1'. Using working directory '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld'. Using root namespace 'HelloWorld'. Using project directory '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/'. Finding DbContext classes... Finding IDesignTimeDbContextFactory implementations... Finding application service provider... Finding IWebHost accessor... Using environment 'Development'. Using application service provider from IWebHost accessor on 'Program'. Found DbContext 'HelloWorldDBContext'. Finding DbContext classes in the project... Using context 'HelloWorldDBContext'. Finding design-time services for provider 'Microsoft.EntityFrameworkCore.Sqlite'... Using design-time services from provider 'Microsoft.EntityFrameworkCore.Sqlite'. Finding design-time services referenced by assembly 'HelloWorld'. No referenced design-time services were found. Finding IDesignTimeServices implementations in assembly 'HelloWorld'... No design-time services were found. Migrating using database 'main' on server 'blogging.db'. Opening connection to database 'main' on server 'blogging.db'. Opened connection to database 'main' on server '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/blogging.db'. Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Executed DbCommand (33ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Opening connection to database 'main' on server 'blogging.db'. Opened connection to database 'main' on server '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/blogging.db'. Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table'; Executed DbCommand (9ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table'; Closing connection to database 'main' on server '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/blogging.db'. Closed connection to database 'main' on server 'blogging.db'. Opening connection to database 'main' on server 'blogging.db'. Opened connection to database 'main' on server '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/blogging.db'. Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Opening connection to database 'main' on server 'blogging.db'. Opened connection to database 'main' on server '/Users/yufei/Developer/aspnetcore/HelloWorld/HelloWorld/blogging.db'. Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] PRAGMA foreign_keys=ON; Executing DbCommand [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND "type" = 'table'; Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30'] SELECT COUNT(*) FROM "sqlite_master" WHERE "name" = '__EFMigrationsHistory' AND轉(zhuǎn)載于:https://www.cnblogs.com/lonelyxmas/p/9724400.html
總結(jié)
以上是生活随笔為你收集整理的ASP.NET Core Identity 迁移数据 - ASP.NET Core 基础教程 - 简单教程,简单编程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: php7 加的新特性积累
- 下一篇: ASP.NET Core2基于Rabbi