I'm using EF 6.0 with LINQ in MVC 5 project. I want to log all the SQL queries executed by the Entity Framework DbContext for debugging/performance-measurement purpose.
我在MVC 5项目中使用EF 6.0和LINQ。我想记录Entity Framework DbContext执行的所有SQL查询,以进行调试/性能测量。
In Java/Hibernate, equivalent behavior can be achieved by setting the property hibernate.show_sql=true
. Is it possible to have a similar behavior in Entity Framework?
在Java / Hibernate中,可以通过设置属性hibernate.show_sql = true来实现等效行为。是否有可能在实体框架中有类似的行为?
2 个解决方案
#1
42
Logging and Intercepting Database Operations article at MSDN is what your are looking for.
MSDN上的日志记录和拦截数据库操作文章正是您所需要的。
The DbContext.Database.Log
property can be set to a delegate for any method that takes a string. Most commonly it is 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. For example, the following code will log SQL to the console:
对于采用字符串的任何方法,可以将DbContext.Database.Log属性设置为委托。最常见的是,它通过将其设置为TextWriter的“Write”方法与任何TextWriter一起使用。当前上下文生成的所有SQL都将记录到该编写器。例如,以下代码将SQL记录到控制台:
using (var context = new BlogContext())
{
context.Database.Log = Console.Write;
// Your code here...
}
#2
16
You can use this line to log only to the "Output" window and not to a console window, again in Debug mode only.
您只能在调试模式下使用此行仅记录到“输出”窗口而不是控制台窗口。
public class YourContext : DbContext
{
public YourContext()
{
Database.Log = sql => Debug.Write(sql);
}
}
#1
42
Logging and Intercepting Database Operations article at MSDN is what your are looking for.
MSDN上的日志记录和拦截数据库操作文章正是您所需要的。
The DbContext.Database.Log
property can be set to a delegate for any method that takes a string. Most commonly it is 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. For example, the following code will log SQL to the console:
对于采用字符串的任何方法,可以将DbContext.Database.Log属性设置为委托。最常见的是,它通过将其设置为TextWriter的“Write”方法与任何TextWriter一起使用。当前上下文生成的所有SQL都将记录到该编写器。例如,以下代码将SQL记录到控制台:
using (var context = new BlogContext())
{
context.Database.Log = Console.Write;
// Your code here...
}
#2
16
You can use this line to log only to the "Output" window and not to a console window, again in Debug mode only.
您只能在调试模式下使用此行仅记录到“输出”窗口而不是控制台窗口。
public class YourContext : DbContext
{
public YourContext()
{
Database.Log = sql => Debug.Write(sql);
}
}