Entity Framework starting from Version 6.0 allows us to log the commands & queries sent to the database. The Logging is done by using the DbContext.Database.Log property, which can be set to a delegate for any method that takes a string. All the actions performed by the Entity Framework is logged, which includes opening a connection, closing a connection, database initialization, Add, Edit, Insert & Select Queries, etc
Logging Database Operations
The simplest way to implement logging is to use the Console.Write Function. The console.write function takes a string as the parameter and writes that string into the console window. This makes it an ideal candidate to use for simple logging. All we need to do this is to assign the write method to DbContext.Database.Log property. The Example Code is shown below
1 2 3 4 5 6 7 8 9 10 | using (EFContext db = new EFContext()) { db.Database.Log = Console.Write; db.Employees.Where(e => e.EmployeeID == 0).ToList(); Console.WriteLine("Press any key to close"); Console.ReadKey(); } |
Custom Logging
You can create a custom logging class and write the log to any place as you wish. You can write a log to a text file or to another database etc. The following code snippets show how to implement the custom logging
The code below EFLogger has a write method that accepts the string as a parameter. Inside the write method, we have sent the logs to the console. You can easily change it to any location of your choice.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public class EFLogger { public void Write(string log) { Console.Write(log); //You can write to a file //Or to a Database here } } static void Main(string[] args) { EFLogger logger = new EFLogger(); using (EFContext db = new EFContext()) { db.Database.Log = s => logger.Write(s); db.Employees.Where(e => e.EmployeeID == 0).ToList(); Console.WriteLine("Press any key to close"); Console.ReadKey(); } } |