Reputation: 576
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.
Upvotes: 6
Views: 3317
Reputation: 205569
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.
Upvotes: 3
Reputation: 40
I think it is better that you can refer to use SQL Server Profiler to capture all the queries to database.
If you are developing locally, SQL Profiler will be ideal for you.
Whatever kind of Linq Queries or Raw SQL Query can be captured by the profiler.
Upvotes: -2