20.1翻譯系列:EF 6中自動數據遷移技術【EF 6 Code-First系列】

原文連接:https://www.entityframeworktutorial.net/code-first/automated-migration-in-code-first.aspxhtml

 

EF 6 Code-First系列文章目錄:數據庫

 

 

Entity Framework介紹了自動遷移技術,因此每次實體發生改變的時候,你不用手動去處理數據庫遷移。app

自動遷移技術能夠經過在程序包管理控制檯中輸入並執行:enable-migrations命令作到。打開程序包管理控制檯,輸入:enable-migrations –EnableAutomaticMigration:$true【確保默認的項目是你如今要執行的項目】less

當命令執行成功以後,將會建立一個internal sealed Configuration 類,這個Configuration類繼承自DbMigrationConfiguration :ide

正如你在COnfiguration類的構造函數中看到的那樣,AutomaticMigrationsEnabled 被設置爲true.函數

下一步,就是在上下文類中設置數據庫初始化策略爲MigrateDatabaseToLatestVersion:測試

public class SchoolContext: DbContext { public SchoolDBContext(): base("SchoolDB") { Database.SetInitializer(new MigrateDatabaseToLatestVersion<SchoolDBContext, EF6Console.Migrations.Configuration>()); } public DbSet<Student> Students { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); } }

如今你就完成了自動化遷移技術的配置。當實體發生改變的時候,EF將會自動進行數據庫遷移。目前爲止,咱們只有一個Student實體,還有一個上下文類,咱們運行項目看看生成的數據庫:ui

你將會發現EF API建立了__MigrationHistory 表和Students表。__MigrationHistory 包含了每次數據庫遷移的歷史記錄。spa

如今,你添加一個新的領域類實體,運行程序,會發現數據庫自動包含了全部實體所映射的表。你不用運行任何其餘命令。.net

然而,這樣只是針對添加實體或者移除實體纔有用,當你向實體中添加、修改或者刪除屬性的時候,並不起做用。刪除領域類的任何一個屬性,運行項目:

這樣是由於你將會丟失相應列的數據。爲了解決這個,你須要在Configuration類的構造函數中,設置AutomaticMigrationDataLossAllowed 爲true,而且設置AutomaticMigrationsEnabled = true。

爲了瞭解更多enable-migrations命令的參數,能夠執行get-help enable-migrations 或者get-help enable-migrations -detailed,你將會看到:

PM> get-help enable-migrations NAME Enable-Migrations SYNOPSIS Enables Code First Migrations in a project. SYNTAX Enable-Migrations [-ContextTypeName <String>] [-EnableAutomaticMigrations] [-MigrationsDirectory <String>] [-ProjectName <String>] [-StartUpProjectName <String>] [-ContextProjectName <String>] [-ConnectionStringName <String>] [-Force] [-ContextAssemblyName <String>] [-AppDomainBaseDirectory <String>] [<CommonParameters>] Enable-Migrations [-ContextTypeName <String>] [-EnableAutomaticMigrations] [-MigrationsDirectory <String>] [-ProjectName <String>] [-StartUpProjectName <String>] [-ContextProjectName <String>] -ConnectionString <String> 
    -ConnectionProviderName <String> [-Force] [-ContextAssemblyName <String>] [-AppDomainBaseDirectory <String>] [<CommonParameters>] DESCRIPTION Enables Migrations by scaffolding a migrations configuration class in the project. If the target database was created by an initializer, an initial migration will be created (unless automatic migrations are enabled via the EnableAutomaticMigrations parameter). RELATED LINKS REMARKS To see the examples, type: "get-help Enable-Migrations -examples". For more information, type: "get-help Enable-Migrations -detailed". For technical information, type: "get-help Enable-Migrations -full".
相關文章
相關標籤/搜索