Chapter 8
What’s Coming Next for Code First
第8章
Code First將走向哪里?
So far, this book has covered all of the Code First components that reached their final release at the time of writing. There are, however, some notable features that are still in preview at this time that you should be aware of. You’ll gain the ability to migrate a database schema as your Code First model evolves, reverse engineer a Code First model from an existing database, and many other useful tasks.
These features are available as add-ons to the EntityFramework NuGet package and can be downloaded separately. Currently there are two add-ons available. The first, the EntityFramework.Migrations NuGet package, adds database migration capabilities to
Code First. The second, Entity Framework Power Tools, provides some extra design time tooling for working with Code First and is available on Visual Studio Gallery.
到目前為止,本書已經覆蓋了Code First組件的所有功能(包含截止本書寫作時的最后一個正式發布版本)。但是還有很多你應該知道的顯著功能已經納入了預覽版本。這些功能包括通過遷移數據庫構架作為Code First的模型,從現在數據庫中逆生成Code First模型和許多其他的有用的功能。
這些特性已經制成Entity Framework NuGget包作為插件進行了發布,可以分別單獨下載。目前就有兩個可用的插件。第一個,EntityFramework.Migrations NuGet package,為Code First添加了數據庫遷移能力。第二個Entity Framework Power Tools,提供了許多Code First的設計時工具,可用於Visural Studio中。
Code First Migrations
Code First的數據庫遷移
Throughout this book we have used database initializers to drop and recreate the database every time the model changes. This is far from ideal, because in doing so, you lose any data every time the model changes. That might be acceptable while you’re developing locally, but it’s definitely not a viable solution once you want to push changes into production! Currently you are forced to use a schema compare tool or a hand-written script to push database changes to the production database.
Since Code First was released, one of the most common requests from the developer community was for a migrations solution. Migrations allow you to incrementally evolve your database schema as your model changes. There are many migration solutions available, but none that are integrated with Code First. Most of these solutions take a similar approach to providing database migration functionality. Each set of changes to the database is expressed in a code file, known as a migration. The migrations are ordered, typically using a timestamp, and a table in the database keeps track of which migrations have been applied to the database.
本書中我們使用數據庫初始化器在每次模型變化時來刪除和重建數據庫。這不夠理想,因為這樣做在每次模型變化時都會丟失數據。在本地開發時這也許是可接受的,但是一旦想將變化放在產品中這絕對不是一個可行的解決方案。現在你被強制使用構架比較 工作或手寫腳本推動數據庫變更到產品數據庫。
自從@CF發布后,來自開發者社區的多個呼聲指向遷移解決方法。遷移允許的數據庫構架隨着Code First模型的變化 逐步演變。現在有很多可用的遷移解決方案,但沒有一個集成在Code First上。多數解決方案在數據庫遷移功能提供了類似的方法。任何一套對數據庫變更都會表達代碼文件中稱之為遷移。遷移是有序的,通常使用一個時間戳和一個數據庫中的表保持跟何種蹤移已應用到數據庫。
The Entity Framework team has been working on providing a migrations solution that is tightly integrated with Code First. Code First Migrations Alpha 3 became available in early September 2011. Details on the Alpha 3 release of Code First Migrations can be found at http://blogs.msdn.com/b/adonet/archive/2011/09/21/code-first-migrations-alpha-3-released.aspx. This early preview is focused on the developer experience inside Visual Studio and allows migrations to be created and executed against the database as your Code First model is changed.
Code First Migrations is available as the EntityFramework.Migrations NuGet package. Once installed, it adds a couple of commands to the Package Manager Console that can be used to generate and run migrations.
As you make changes to your Code First model, you can ask Code First Migrations to create a migration that will apply the corresponding changes to the database. Migrations are expressed in code, and once a migration has been created, you are free to edit the code that was generated for you. Example 8-1 shows what a migration can look like.
@EF團隊一直致力於提供一個遷移解決方案,能夠緊密集成在Code First。Code First遷移Alpha3已經在2011年9月月初發布。Alpha3發布的詳細信息,可以在http://blogs.msdn.com/b/adonet/archive/2011/09/21/code-first-migrations-alpha-3-released.aspx找到。這種早期預覽版聚焦於在Visual Studio的開發體驗,並在Code First模型發生改變時允許遷移到已創建和執行過的數據庫上。
Code First目前已經發布了EntityFramework.Migrations NuGet包。一旦安裝完畢,它增加了一組命令到包管理器控制台,可用於生成和運行遷移命令。
當Code First模型變化后,你可以要求@CF遷移到創建一個遷移,應用相應的變化到數據庫。遷移使用代碼表示,一旦遷移已經創建,您可以自由編輯為您生成的代碼。例8-1給出了遷移的代碼樣例。
Example 8-1. Sample migration
namespace BreakAway.Migrations { using System.Data.Entity.Migrations; public partial class SampleChanges : DbMigration { public override void Up() { AddColumn( "Destinations", "Description", c => c.String()); ChangeColumn( "Destinations", "Name", c => c.String(maxLength: 100)); } public override void Down() { ChangeColumn( "Destinations", "Name", c => c.String()); DropColumn( "Destinations", "Description"); } } }
The migrations are expressed using an API that is similar to the Fluent API you’ve been using to configure the model. In the example, you can see that a Description column is being added to the Destinations table and the Name column is having its maximum length changed to 50. A provider model is used to translate the operations defined in code into database specific SQL.
Code First Migrations also supports automatic migrations, which allow simple changes, such as column additions, to be performed without having a migration present in your project. You can use automatic migrations and code-based migrations in the same solution to allow the correct level of control for each change you make.
遷移用類似於Fluent API的API來表達。在上述例子中,你可以看到一個描述列被添加到Destinations表中,而Name列的最大長度改為50。provider模型是用來將代碼中的具體操作轉化成數據庫特定的SQL代碼。
Code First遷移還支持自動遷移,允許簡單的變化,如列增加,執行,可以在項目沒有遷移存在的情況下執行。您可以同一解決方案中同時使用自動遷移和基於代碼的遷移,讓你所做的每個更改都處於正確的控制水平。
Entity Framework Power Tools
Entity Framework工具
The first Entity Framework Power Tools Community Technical Preview (CTP 1) was made available in May 2011. This package can be installed through the Visual Studio Extension Manager or downloaded directly from the Visual Studio Gallery at http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d.
Once installed, the Power Tools add designer tools to Visual Studio that can be accessed through context menus in the Visual Studio Solution Explorer.
@EF Power Tools社區預覽版(CTP1)於2011年5月發布。這個安裝包可以通過VS擴展管理器進行安裝,也可 以直接從VS Gallery下載:http://visualstudiogallery.msdn.microsoft.com/72a60b14-1581-4b9b-89f2-846072eff19d.
一旦安裝,Power Tools會在VS中添加一些設計時工作,可以通過VS解決方案瀏覽器的上下文菜單來訪問。
Reverse Engineer Code First
Code First逆向工程
With this designer tool installed, you’ll find a new menu option—Entity Framework—on the project context menu in Solution Explorer (Figure 8-1). The new item has a submenu item called “Reverse Engineer Code First.” Selecting this option will prompt you to point to an existing database that you would like to map classes to using Code First. The tool will use the schema of the database to generate a Code First context, a set of POCO classes, and a set of configuration classes to map the POCO classes to the database. You can see what these classes look like in the blog post “Quick Look at Reverse Engineer DB into Code First Classes”.
The reverse engineer process is designed to be a one-time code generation to get you started against an existing database. Once the code is generated, you may need to tweak it to match your exact database schema. For example, CTP1 does not generate the correct mapping code for tables that are not in the dbo schema. If you have tables in another schema, you would need to edit the ToTable call in the relevant configuration objects to specify the correct schema.
CTP1 of the Power Tools only supports reverse engineering to C#. The Entity Framework team will introduce VB.NET capabilities in a future release.
設計工具的安裝后,你會發現在解決方案資源管理器中項目的上下文菜單中出現了一個新的菜單選項—“Enity Framework”(圖8-1)。新項下,有一個”Reverse Engineer Code First“子菜單項。選擇此選項,會提示你指向一個現有的數據庫,這個數據庫就是您想使用Code First類來映射的數據庫。該工具將會使用數據庫的架構產生一個Code First的context,一系列POCO類,以及POCO類映射到數據庫的配置設置。在博客文章“Quick Look at Reverse Engineer DB into Code First Classes”,你可以看到這些類看起來像什么。
逆向工程過程的設計為對現有數據庫一次性實施代碼生成。一旦生成代碼,您可能需要調整,以滿足您的的數據庫架構。例如,CTP1不會對dbo架構生成正確的代碼。如果你有另一個構架中的表,您將需要編輯ToTable調用相關的配置對象來指定正確的構架。
Power Tools CTP1只支持逆向工程到C#。Entity Framework團隊將在未來版本中引入生成VB.NET的能力。
Figure 8-1. Project context menu
Viewing a Code First Model
查看Code First模型
The Entity Framework Power Tools also adds an Entity Framework item to the context
menu for classes that inherit from DbContext (Figure 8-2). When you right-click the
code file in Solution Explorer, this Entity Framework entry has four options. The first
three provide you different views of the model for the selected context.
@EF Power Tools還在“Entity Framework”項中添加了針對繼承自DbContext的類的上下文菜單項(圖8-2)。當在解決方案資源管理器左鍵單擊代碼文件時,Entity Framework 就有了四個選項,前三個提供了模型的不同查看方式:
Figure 8-2. Code First context menu
View Entity Data Model (Read-only)
查看實體數據模型(只讀)
The “View Entity Data Model (Read-only)" option will launch the Entity Data Model designer and display the model defined by the context. The Power Tools achieve this by writing out a temporary EDMX file that represents the model and opening it with the designer.
This is a read-only view of the model, and any changes you make will not result in changes being made to your code. You are only able to make changes because the designer, which ships as part of Visual Studio, does not have a read-only mode.
The ability to view the model can be useful if you are trying to work out how Code First is interpreting your classes and configuration. The designer also displays mapping so you can see how Code First is mapping your classes and properties to columns and tables in the database.
“View Entity Data Model(Read Only)”選項將啟動Entity Data Model設計器顯示定義在context中的模型。Power Tools通過創建了一個臨時的代表模型的EDMX文件實現此功能並將其在設計器中打開。
這是對模型的只讀查看,任何在設計器的更改不會對代碼有任何改變。你能做修改是由於設計品是VS的一部分,沒有只讀模式。查看模型能力在你試圖解析Code First如何表達類與配置時是有用的。設計器也顯示映射,因此你可以看到Code First如何映射你的類和屬性到數據庫的表和列中。
View Entity Data Model XML
查看實體數據模型XML
The “View Entity Data Model XML” option will load up the EDMX equivalent of your Code First model in the XML editor.
This option is primarily used by the Entity Framework team to identify issues in the model that is being generated by Code First.
“View Entity Data Model XML”選項在XML編輯器中載入等價於@CF模型的EDMX文件。
這個選項主要用來給Entity Framework團隊識別Code First生成模型存在的問題。
View Entity Data Model DDL SQL
查看實體數據模型DDL SQL
The View Entity Data Model DDL SQL option allows you to generate the same SQL script that Code First would use to generate a database from your model. This can be useful if you have been developing with Code First and now need to hand a SQL script off to your DBA to create a production database.
“View Entity Data Model DDL SQL ”選項用於生成與Code First用來從模型生成數據庫所用的SQL腳本相同的腳本。在使用Code First開發中可能會用到,因為目前需要手寫SQL腳本來創建最終產品數據庫。
Optimize Entity Data Model
優化實體數據模型
The fourth option in the Entity Framework menu item that’s attached to the context class is “Optimize Entity Data Model.” This allows you to perform view generation on your Code First model.
在@EF中的上下文菜單項目的第四個選項是“優化實體數據模型。”從而允許您使用Code First模型執行視圖生成。
View generation is a process that Entity Framework performs to calculate the SQL statements that will be used to Select, Insert, Update, and Delete for each type in your model. This process typically occurs the first time you use your context within an application process. If you have a large and/or complex model, view generation can be an expensive operation, taking several minutes or even hours in very large models.
視圖生成是一個過程,這個過程中Entity Framework執行一些SQL語句計算,這些語句可用於在模型中對每個類型進行選擇,插入,更新,刪除。這個過程通常發生在您第一次在應用程序進程中使用上下文時。如果你有一個大的和/或復雜的模型,視圖生成是一項耗費資源的操作,非常大的模型在需要幾分鍾甚至幾小時。
To avoid incurring this cost every time your application runs, you can use Pre-Compiled Views. That’s exactly what this option does: it precalculates the SQL and stores it in a code file in your project. Entity Framework will pick up this code at runtime and use the precalculated views rather than performing View generation. If you change your model after performing view generation, you will need to rerun this option to calculate the views again.
Pre-Compiled Views are a fairly advanced feature, and it is not recommended that you use them unless you hit a performance issue related to View Generation.
Pre-compilation and view generation are not unique to Code First. These features have been available for EDMX files since the first version of Entity Framework. The Power Tools simply let you also take advantage of these features when using Code First. You can read more about precompiled views and view generation in Chapter 20 of Programming Entity Framework, second edition.
為了避免產生這種每次應用程序運行發生的問題,你可以使用預編譯的視圖。這正是此選項要做的工作:它預先計算 SQL並存儲在一個項目中的代碼文件中。@EF將在運行時執行這些代碼,使用預計算的視圖,而不是執行視圖生成。執行視圖生成后如果模型發生改變,需要重新運行此選項再次計算視圖。
預編譯視圖是相當先進的功能,這里不建議您使用它們,除非你遇到了有關於視圖生成相關的性能問題。
預編譯和視圖生成不只存在於Code First中。這些功能已在EDMX文件中實現,並在Entity Framework第一個版本就有了。Power Tools簡單地讓你能夠在Code First中使用這些功能。你可以閱讀更多有關預編譯視圖和視圖生成的內容,見Programing Entity Framework,第二版的第20章。
Following the Entity Framework Team
There are a number of ways you can keep up to date on new features that the Entity Framework team is developing—and even influence what features they work on next.The ADO.NET Team Blog is used by the EF team to share announcements about new and upcoming releases. The EF team also has an EF Design Blog, where they share early thinking about new features they are about to start working on. This allows you to have input into the design of features before they are implemented and end up in a preview. Finally, the EF team has a user voice site where you can add and vote on feature requests.
小貼士:
追隨@EF團隊
有一些方法可以使你保持獲取Entity Framework團隊開發的的新功能---甚至影響他們的工作的方向。The ADO.NET團隊博客與EF團隊共同分享最新發布的公告信息。@EF團隊也有專用的設計博客,在那里可以早期獲取新功能 的想法以及將要開始開發的功能。這允許您在開發團階段實施和發布預覽版本之前將您的設計需求輸入到Entity Framework的設計特征中去。最后,EF的團隊有一個用戶之聲網站,您可以添加和為新功能要求投票。