通过实体框架的DbContext执行日志查询 [英] Log Queries executed by Entity Framework DbContext
问题描述
我在MVC 5项目中使用EF 6.0 LINQ。我想记录所有的实体框架的DbContext调试/性能测量目的执行的SQL查询。
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.
在Java /休眠,相当于行为可以通过设置属性 hibernate.show_sql = TRUE
实现。是否有可能在实体框架有类似行为?
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?
推荐答案
Logging and Intercepting Database Operations article at MSDN is what your are looking for.
的 DbContext.Database.Log
属性可以设置为一个委托,它接受一个字符串的任何方法。最常见的是通过将其设置到的TextWriter的写的方法用于任何的TextWriter
。在目前的情况下产生的所有SQL语句将被记录到作家。例如,下面的code将SQL登录到控制台:
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:
using (var context = new BlogContext())
{
context.Database.Log = Console.Write;
// Your code here...
}
这篇关于通过实体框架的DbContext执行日志查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!