How do I view the SQL generated by the Entity Framework?

后端 未结 22 2914
别那么骄傲
别那么骄傲 2020-11-21 05:35

How do I view the SQL generated by entity framework ?

(In my particular case I\'m using the mysql provider - if it matters)

22条回答
  •  长发绾君心
    2020-11-21 06:13

    Use Logging with Entity Framework Core 3.x

    Entity Framework Core emits SQL via the logging system. There are only a couple of small tricks. You must specify an ILoggerFactory and you must specify a filter. Here is an example from this article

    Create the factory:

    var loggerFactory = LoggerFactory.Create(builder =>
    {
        builder
        .AddConsole((options) => { })
        .AddFilter((category, level) =>
            category == DbLoggerCategory.Database.Command.Name
            && level == LogLevel.Information);
    });
    

    Tell the DbContext to use the factory in the OnConfiguring method:

    optionsBuilder.UseLoggerFactory(_loggerFactory);
    

    From here, you can get a lot more sophisticated and hook into the Log method to extract details about the executed SQL. See the article for a full discussion.

    public class EntityFrameworkSqlLogger : ILogger
    {
        #region Fields
        Action _logMessage;
        #endregion
        #region Constructor
        public EntityFrameworkSqlLogger(Action logMessage)
        {
            _logMessage = logMessage;
        }
        #endregion
        #region Implementation
        public IDisposable BeginScope(TState state)
        {
            return default;
        }
        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }
        public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter)
        {
            if (eventId.Id != 20101)
            {
                //Filter messages that aren't relevant.
                //There may be other types of messages that are relevant for other database platforms...
                return;
            }
            if (state is IReadOnlyList> keyValuePairList)
            {
                var entityFrameworkSqlLogMessage = new EntityFrameworkSqlLogMessage
                (
                    eventId,
                    (string)keyValuePairList.FirstOrDefault(k => k.Key == "commandText").Value,
                    (string)keyValuePairList.FirstOrDefault(k => k.Key == "parameters").Value,
                    (CommandType)keyValuePairList.FirstOrDefault(k => k.Key == "commandType").Value,
                    (int)keyValuePairList.FirstOrDefault(k => k.Key == "commandTimeout").Value,
                    (string)keyValuePairList.FirstOrDefault(k => k.Key == "elapsed").Value
                );
                _logMessage(entityFrameworkSqlLogMessage);
            }
        }
        #endregion
    }
    

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题