当前位置:Gxlcms > 数据库问题 > Entity Framework 6.0 Tutorials(4):Database Command Logging

Entity Framework 6.0 Tutorials(4):Database Command Logging

时间:2021-07-01 10:21:17 帮助过:3人阅读

(var context = new SchoolDBEntities()) { context.Database.Log = Console.Write; var student = context.Students .Where(s => s.StudentName == "Student1").FirstOrDefault<Student>(); student.StudentName = "Edited Name"; context.SaveChanges(); }

 

Output:

技术分享

You can see in the output that it logs all the activities performed by EF, e.g. opening & closing connection, execution & completion time and database queries & commands.

Context.Database.Log is an Action<string> so that you can attach any method which has one string parameter and void return type. For example:

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 student = context.Students
                                .Where(s => s.StudentName == "Student1").FirstOrDefault<Student>();

                student.StudentName = "Edited Name";
                context.SaveChanges();
            }
        }
}

 

Download DB First sample project for DB command logging demo.

Entity Framework 6.0 Tutorials(4):Database Command Logging

标签:

人气教程排行