I want to log the Entity Framework queries in my debug window. I could do that with the following line:
myContext.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
But how can I do that for all my queries in different functions and in different files?
Do I have to write this line everywhere?
Or is there a way to do this by writing a particular line of code to log every query at a single place.
As suggested, I have written the code in the constructor of the context but it's not working.
public partial class EkartEntities : DbContext
{
public EkartEntities() : base("name=EkartEntities")
{
Database.Log = s => System.Diagnostics.Debug.WriteLine(s);
}
}
Am I doing something wrong?
Also, it is not duplicate of How to make EF log sql queries globally? as the post contains the answer of Code-First approach where we can simply modify our constructor.
You can install global logger by adding the following class to the project containing your DbContext
derived class:
class MyDbConfiguration : System.Data.Entity.DbConfiguration
{
public MyDbConfiguration()
{
AddInterceptor(new System.Data.Entity.Infrastructure.Interception.DatabaseLogFormatter(
s => System.Diagnostics.Debug.WriteLine(s)));
}
}
The class represents the so called Code-based configuration and in this particular case is used to automatically register DatabaseLogFormatter
with the specified Action<string>
for all DbContext
derived types and instances in the project that contains it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With