Entity Framework 4.0: How to see SQL statements for SaveChanges method

后端 未结 6 715
长发绾君心
长发绾君心 2020-12-09 02:26

I used to use the context.Log for tracing LINQ to SQL generated SQL Statements as shown in Sql Server Query Visualizer – Cannot see generated SQL Query

conte         


        
6条回答
  •  天涯浪人
    2020-12-09 02:56

    Expanding on Nate's answer for EF6, the NLogCommandInterceptor seen in Logging and Intercepting Database Operations only shows the CommandText.

    If there was some particular parameter value that caused that commandText to fail, the parameters values aren't emitted to the log. In my case I wanted to log what values were causing Foreign Key violations.

    This can be improved by altering NLogCommandInterceptor's LogIfError method like thus

    private void LogIfError(DbCommand command, DbCommandInterceptionContext interceptionContext)
    {
        if (interceptionContext.Exception != null)
        {
            var commandDumper = new DbCommandDumper(command);
            Log.Warn(Command failed:\r\n{0}", commandDumper.GetLogDump());
            // Exception will get logged further up the stack
        }
    }
    

    where the DbCommandDumper class reconstructs the DbCommand into TSQL that can be replayed into a test database.

提交回复
热议问题