简体   繁体   中英

Retrieving SQL Generated by Entity Framework Core

I'm trying to retrieve the raw SQL generated by Entity Framework for the following LINQ query:

pagedItemResults = from firstItem in dbData.Accession
                        join secondItem in pagedRowNumberResults
                        on firstItem.AccessionNumber equals secondItem
                        select new PaginationResultRow
                        {
                            Number = firstItem.AccessionNumber,
                            ID = firstItem.AccessionId,
                            Name = firstItem.AcquisitionType.Name,
                            Description = firstItem.Description
                        };

Although it may be extremely simple and similar to the other answers already out there for previous versions of EF, I've had no luck and found nothing online.. any ideas??

You can turn on logging by implementing ILoggerProvider . See details in documentation.

You only need to register the logger with a single context instance. Once you have registered it, it will be used for all other instances of the context in the same AppDomain.

        using (var db = new BloggingContext())
        {
            var serviceProvider = db.GetInfrastructure<IServiceProvider>();
            var loggerFactory = serviceProvider.GetService<ILoggerFactory>();
            loggerFactory.AddProvider(new MyLoggerProvider());
        }

You can also define categories what you want to log.

    private static string[] _categories =
    {
        typeof(Microsoft.Data.Entity.Storage.Internal.RelationalCommandBuilderFactory).FullName,
        typeof(Microsoft.Data.Entity.Storage.Internal.SqlServerConnection).FullName
    };

You can log tsql generated to output window by :

Microsoft.Extensions.Logging.Debug

First, get it from Nuget , then in your context, you must define a LoggerFactory .

After that, use it in OnConfiguring in your context.

public static readonly Microsoft.Extensions.Logging.LoggerFactory _loggerFactory =
                    new LoggerFactory(new[] {
                    new Microsoft.Extensions.Logging.Debug.DebugLoggerProvider()
    });

optionsBuilder.UseLoggerFactory(_loggerFactory);

I really like MiniProfiler, see http://miniprofiler.com/ . Short of something like this, I would say you'd have to use a profiler on the actual database.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM