码迷,mamicode.com
首页 > 数据库 > 详细

EF6基础系列(17)---记录数据库命令

时间:2018-09-13 20:01:00      阅读:212      评论:0      收藏:0      [点我收藏+]

标签:--   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();
        }
    }
}

 

EF6基础系列(17)---记录数据库命令

标签:--   inf   base   and   pre   ati   现在   执行   color   

原文地址:https://www.cnblogs.com/wyy1234/p/9642131.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!