Logging Database Operations in Entity Framework 6 (EF6 New Feature)

In this article you will learn the new feature "Logging Database Operations" introduced with Entity Framework 6. This features works for models created with Code First or the EF Designer.

This new feature gives us the opportunity to log every command and query sent to the database. This is the easiest way to see what's happening with the database under the hood. In the past, we fire up SQL Profiler by installing SQL Server Management Studio and configure it just to see what EF request is running and a whole bunch of stuff. So, now we have this feature integrated with EF6. The primary use of this feature is to debug unexpected behavior/results and troubleshoot performance issues by looking at an execution report such as the time required to execute a query and so on. This also helps us to see how EF translates a LINQ query into a SQL query.
 
In my previous article of this series "Custom Code First Conventions", I already setup a console application, here I'm going to use that application to explore this logging feature. However you can try it with any application you want. So, let's directly jump and talk about Logging Database Operations.
 
We can log database operations, on the command line or at a different location.
 
Logging at the Command Line
 
Look at the following code, its simple and self-explanatory, the only thing new here is the write DbContext.Database.Log command at the beginning. The DbContext.Database.Log property can be set to a delegate for any method that takes a string. In particular, it can be used with any TextWriter by setting it to the "Write" method of that TextWriter. All SQL generated by the current context will be logged to that writer. In the example given below, DbContext.Database.Log is set to Console.Write.
  1. class Program  
  2. {  
  3.     static void Main(string[] args)  
  4.     {  
  5.         using (var context = new StateContext())  
  6.         {  
  7.             context.Database.Log = Console.Write;  
  8.    
  9.             InsertRecords(context);  
  10.             SelectRecords(context);  
  11.             Console.ReadKey();  
  12.         }  
  13.     }  
  14.    
  15.     private static void SelectRecords(StateContext context)  
  16.     {  
  17.         var stdQuery = (from d in context.States  
  18.                         select new { StateName = d.StateName });  
  19.         foreach (var q in stdQuery)  
  20.         {  
  21.             Console.WriteLine("Name : " + q.StateName);  
  22.         }  
  23.     }  
  24.    
  25.     private static void InsertRecords(StateContext context)  
  26.     {  
  27.         context.States.Add(new State { StateName = "State " + (context.States.Count() + 1)});  
  28.         context.SaveChanges();  
  29.     }  
  30. }  

Once I executed the code above, it displayed an abudance of queries to the command line. If you take a closer look at the code above, you will find three different queries expected to execute and the same thing happens, you can see it in the log. You will see extra log information also that includes all the work that the migrations does under the covers to check for or create a new database. Here is the output.

1.png

In the preceding output you will see that the following things got logged for you.
  1. SQL Commands including relationships generated by Lazy Loading, you can't see it in the output above ;)
  2. Parameters
  3. Timestamp with information like asynchronous query or not
  4. Completed, Failed, Cancelled command information with the time it took and so on
Now, let's look at a way to log this information to a different location.
 
Logging to different location
 
It is also easy to log to memory, a file, a database and so on using various kinds of TextWriter. In the example given below, I have a class "MyLogger" with a method "Log" that accepts a string and writes it to console.

2.png

We can do more things, such as change the log format and customize it by writing a class that inherits "DatabaseLogFormatter".
 
Hope it helps.
 
Thanks.

Up Next
    Ebook Download
    View all
    Learn
    View all