a blog for those who code

Monday 24 April 2017

How to Log Database Commands in Entity Framework

In this post we will be discussing about how to log database commands and queries sent to the database from the Entity Framework. Its always better to log whatever activities you are doing on your database to find out any suspicious activities. We will show the simplest example how to log database commands and queries using Entity Framework 6.

We will be using Log method of Database class which is to log the SQL generated by the System.Data.Entity.DbContext to the given delegate. You can also change the format of the log text by creating a new formatter. You can see the log in various different ways i.e. either you can save the log into a file or you can trace that into an output window etc.

Lets first write code to trace the Command Log into the output window as shown below :

db.Database.Log = log => Trace.Write(log);
if (ModelState.IsValid)
{
  db.Transactions.Add(transaction);
  db.SaveChanges();
}
return View();


In the above code we are tracing the log which will logs all the activities performed by Entity Framework e.g. opening & closing connection, execution & completion time and database queries and commands as shown below :


If you want to append a log into a text file then you will change the code as shown below

db.Database.Log = log => File.AppendText("Log_File_Path").WriteLine(log);

Please Like and Share CodingDefined.com blog, if you find it interesting and helpful.



No comments:

Post a Comment