标签:-- inf base and pre ati 现在 执行 color
这一节介绍EF6怎么记录发送给数据库的查询和操作命令。
以前给了查看EF发送给数据库的命令我们需要借助数据库的追踪工具或者第三方追踪工具,现在EF6中提供了DbContext.Database.Log属性(Action<string>类型),使用这个属性我们可以很方便地记录EF发送给数据库的命令。
下边是一个栗子:
static void Main(string[] args) { using (EFDbContext context=new EFDbContext()) { context.Database.Log = Console.WriteLine; var std1 = context.Students.Find(1); std1.Name = "newName"; context.SaveChanges(); Console.ReadKey(); } }
输出如下:
在上边的栗子中,Console.Write()方法属于Action<string>类型,所以可以赋值给Log属性。可以看到EF打开和关闭数据库,执行查询,和使用事务进行CUD都会被记录下来。
我们也可以自定义一个Action<string>委托的实例赋值给Log属性:
public class Logger { public static void Log(string message) { Console.WriteLine("EF Message: {0} ", message); } } class EF6Demo { public static void DBCommandLogging() { using (var context = new SchoolDBEntities()) { context.Database.Log = Logger.Log; var std1 = context.Students.Find(1); std1.Name = "newName"; context.SaveChanges(); Console.ReadKey(); } } }
标签:-- inf base and pre ati 现在 执行 color
原文地址:https://www.cnblogs.com/wyy1234/p/9642131.html