Here, you will learn how to log commands & queries sent to the database by Entity Framework 6.
Prior to EF 6, we used the database tracing tool or a third-party tracing utility to trace database queries and commands sent by Entity Framework.
Now, EF 6 provides the DbContext.Database.Log
property to log the SQL generated by DbContext
.
The Log
property is of Action<string>
type, so you can attach a delegate method with the string parameter and return void
.
The following example demonstrates logging EF activities to the console.
using (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:
In the above example, the Console.Write()
method is attached to the Log
property because it accepts the string
parameter and returns void
.
You can see in the output that it logs all the activities performed by EF, e.g. opening & closing the connection, execution & completion time and database queries & commands.
You can attach a method of your custom class to the Log
property.
The following example uses the method of custom class to log the SQL.
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(); } } }