PC.*_*PC. 35 c# linq entity-framework entity-framework-6 asp.net-mvc-5
我在MVC 5项目中使用EF 6.0和LINQ.我想记录Entity Framework DbContext执行的所有SQL查询,以进行调试/性能测量.
在Java/Hibernate中,可以通过设置属性来实现等效行为hibernate.show_sql=true
.是否有可能在实体框架中有类似的行为?
And*_*rew 56
MSDN上的日志记录和拦截数据库操作文章正是您所需要的.
DbContext.Database.Log
可以将该属性设置为任何采用字符串的方法的委托.最常见的是,TextWriter
它通过将其设置为TextWriter的"Write"方法而与any一起使用.当前上下文生成的所有SQL都将记录到该编写器.例如,以下代码将SQL记录到控制台:
using (var context = new BlogContext())
{
context.Database.Log = Console.Write;
// Your code here...
}
Run Code Online (Sandbox Code Playgroud)
小智 32
您只能在调试模式下使用此行仅记录到"输出"窗口而不是控制台窗口.
public class YourContext : DbContext
{
public YourContext()
{
Database.Log = sql => Debug.Write(sql);
}
}
Run Code Online (Sandbox Code Playgroud)
如果您有一个带有记录器的 .NET Core 设置,那么 EF 会将其查询记录到您想要的任何输出:调试输出窗口、控制台、文件等。
您只需要在应用设置中配置“信息”日志级别。例如,这有 EF 日志记录到调试输出窗口:
"Logging": {
"PathFormat": "Logs/log-{Date}.txt",
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Information",
"System": "Information",
"Microsoft": "Information"
}
},
"Console": {
"LogLevel": {
"Default": "Information",
"System": "Warning",
"Microsoft": "Warning"
}
},
"File": {
"LogLevel": {
"Default": "Information",
"System": "Warning",
"Microsoft": "Warning"
}
},
"LogLevel": {
"Default": "Information",
"System": "Warning",
"Microsoft": "Warning"
}
}
Run Code Online (Sandbox Code Playgroud)
EF Core 日志记录自动与 .NET Core 的日志记录机制集成。如何使用它登录到控制台的示例:
public class SchoolContext : DbContext
{
//static LoggerFactory object
public static readonly ILoggerFactory loggerFactory = new LoggerFactory(new[] {
new ConsoleLoggerProvider((_, __) => true, true)
});
//or
// public static readonly ILoggerFactory loggerFactory = new LoggerFactory().AddConsole((_,___) => true);
public SchoolContext():base()
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseLoggerFactory(loggerFactory) //tie-up DbContext with LoggerFactory object
.EnableSensitiveDataLogging()
.UseSqlServer(@"Server=.\SQLEXPRESS;Database=SchoolDB;Trusted_Connection=True;");
}
public DbSet<Student> Students { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
如果您想登录到输出窗口,请使用以下命令:
public static readonly ILoggerFactory loggerFactory = new LoggerFactory(new[] {
new DebugLoggerProvider()
});
Run Code Online (Sandbox Code Playgroud)
https://www.entityframeworktutorial.net/efcore/logging-in-entityframework-core.aspx
归档时间: |
|
查看次数: |
34659 次 |
最近记录: |