Entity Framework 6新功能Logging/Store Procedure
-
摘要
在Entity Framework6中有两个新的功能,DB Loggin和Stored Procedure的映射
Entity Framework 6已经从Beta版本来到了RC1版本,我们可以看到升级之后EF6有两个亮眼的新功能,DB Logging和CRUD的Stored Procedure映射。
EF6从Beta到RC1添加了什么
在Visual Studio2013中要将原本项目采用的EF6 Beta升级到RC1是一件很简单事,只需要在套件管理主控台输入: update-package EntityFramework -pre
前置作业首先建立一个测试用的模型:TestModel。

图1. TestModel
接下来撰写这个TestModels档案的内容:
01.publicclassTestModel02.{03.[ Key]04.publicintTestId {get;set; }05.publicstringTestName {get;set; }06.}07.08.publicclassTestContext : DbContext09.{10.publicDbSet< TestModel> TestModels {get;set; }11.publicTestContext()12.:base("DefaultConnection")13.{ }14.15.protectedoverridevoidOnModelCreating( DbModelBuilder mb)16.{17.mb.HasDefaultSchema("Test");18.base.OnModelCreating(mb);19.}20.}为了让整个Entity Framework启动起来,我们到HomeController中写一些无意义的程序代码:
1.publicActionResult Index()2.{3.using( TestContext ctx =newTestContext())4.{5.ctx.TestModels.ToList();6.}7.returnView();8.}按下F5执行整个项目后,由于是第一次加载且启动Entity Framework机制,故会等比较久。当首页开启来后检查一下数据库是否已建立TestModel这张数据表。

图2. SQL Server对象总管的画面
前置作业完成之后,接下来就把Entity Framework 6 RC1的两项新功能一一启用。
EF Code First - Stored Procedure映射
数据库产品有着许多与OR/M映射不匹配的状况,EF 6因此引入一个新的功能到Code First中,让开发人员能够更容易的操作数据库。欲在TestModel中启用Stored Procedure,只需在其Context的OnModelCreating方法中添加如下程序代码:
1.protectedoverridevoidOnModelCreating(DbModelBuilder mb)2.{3.mb.HasDefaultSchema("Test");4.mb.Entity< TestModel>()5..MapToStoredProcedures();6.base.OnModelCreating(mb);7.}MapToStoreProcedures()方法具有两个多载,其一为无参数,使用预设Code First的StoreProcedure建构方法来建立Stored Procedure;另一个则有一个Action型别的输入参数,让开发人员可以客制化目前现存的Stored Procedure其:名称,参数...等等。
如果在这个时候直接执行会发生错误,这是因为我已经修改了Code First中的Context程序,并且因此与数据库中现行的内容出现了差异,故需要在套件管理器中执行以下命令:
Enable-Migrations -ContextTypeName EF6Test.Models.TestContext
待执行完毕后,可以发现到项目的档案结构已经出现了一个名为Migrations的数据夹:
若单单只有启动Entity Framework的移转功能但却没有实际将我们本次修改的内容进行明确的宣告,则此次的修改仍不会被纪录起来;而每次修改Code First的POCO或是Context类别后都需要进行结构异动的移转宣告。本次异动移转宣告指令如下:
Add-Migration TestStoredProcedure
执行完命令后会在项目中新增一个[日期时间]_TestStoredProcedure的类别档,打开后可以看到其产生的StoredProcedure。
01.publicpartialclassTestStoredProcedure : DbMigration02.{03.publicoverridevoidUp()04.{05.CreateStoredProcedure(06."Test.TestModel_Insert",07.p =>new08.{09.TestName = p.String(),10.},11.body:12.@"INSERT [Test].[TestModels]([TestName])13.VALUES (@TestName)14.DECLARE @TestIdint15.SELECT @TestId = [TestId]16.FROM [Test].[TestModels]17.WHERE @@ROWCOUNT > 0 AND [TestId] = scope_identity()18.SELECT t0.[TestId]19.FROM [Test].[TestModels] AS t020.WHERE @@ROWCOUNT > 0 AND t0.[TestId] = @TestId"21.);22.23.CreateStoredProcedure(24."Test.TestModel_Update",25.p =>new26.{27.TestId = p.Int(),28.TestName = p.String(),29.},30.body:31.@"UPDATE [Test].[TestModels]32.SET [TestName] = @TestName33.WHERE ([TestId] = @TestId)"34.);35.36.CreateStoredProcedure(37."Test.TestModel_Delete",38.p =>new39.{40.TestId = p.Int(),41.},42.body:43.@"DELETE [Test].[TestModels]44.WHERE ([TestId] = @TestId)"45.);46.}47.48.publicoverridevoidDown()49.{50.DropStoredProcedure("Test.TestModel_Delete");51.DropStoredProcedure("Test.TestModel_Update");52.DropStoredProcedure("Test.TestModel_Insert");53.}54.}从上述程序代码可以看到DBMigration类别已经自动产出了Stored Procedure内容: Insert/Update/Delete。但却没有Select ??
接下要将Stored Procedure在数据库中建立,故,一样在套件管理控制台输入: update-database

图3. 更新数据库
使用DB Logging来监控EF的活动
DB Logging将EF与数据库之间的互动都纪录下来。早前有两个非常棒的ASP.Net套件:MiniProfiler以及Glimpse;它们让我们可以看到EF的SQL陈述句,如今,EF也提供了这项功能。DB Logging主要目标是提供:
1. 了解EF的Linq是怎么转译成SQL陈述句
2. 深入探索那些可能会造成执行时间过长的查询
3. 找出EF没有正确回传结果的原因
启动侦错很简单,仅需指派一个带字符串输入参数的Action对象即可。
1.publicActionResult Index()2.{3.using(TestContext ctx =newTestContext()) {4.ctx.Database.Log = (log) => { Debug .WriteLine(log); };5.ctx.TestModels.ToList();6.}7.returnView();8.}现在,当我们执行应用程序并且浏览到首页面。
假若我们打开侦错主控台窗口,我们会看到"Select ..."这个SQL陈述句共花费12ms于整个执行,而其回传结果为SqlDataReader。

图4. DB Logger所纪录的项目
整齐干净,假若我们想要客制化纪录的字符串呢?EF提供了许多扩充点可以让我们做出像是Glimpse的纪录和追踪功能。
浙公网安备 33010602011771号