Code First :使用Entity. Framework编程(8) ----转发 收藏
第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的团队有一个用户之声网站,您可以添加和为新功能要求投票。