بررسی روش مشاهده خروجی SQL حاصل از کوئریهای Entity framework Core
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۰۹/۲۲ ۱۴:۵۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System;
using Microsoft.Extensions.Logging;
namespace Tests
{
public class MyLoggerProvider : ILoggerProvider
{
public ILogger CreateLogger(string categoryName)
{
return new MyLogger();
}
public void Dispose()
{ }
private class MyLogger : ILogger
{
public bool IsEnabled(LogLevel logLevel)
{
return true;
}
public void Log<TState>(
LogLevel logLevel,
EventId eventId,
TState state,
Exception exception,
Func<TState, Exception, string> formatter)
{
//File.AppendAllText(@"C:\temp\log.txt", formatter(state, exception));
Console.WriteLine("");
Console.WriteLine(formatter(state, exception));
}
public IDisposable BeginScope<TState>(TState state)
{
return null;
}
}
}
} if (logLevel == LogLevel.Critical || logLevel == LogLevel.Error || logLevel == LogLevel.Warning)
using (var db = new MyContext())
{
var loggerFactory = (ILoggerFactory)db.GetInfrastructure().GetService(typeof(ILoggerFactory));
loggerFactory.AddProvider(new MyLoggerProvider());
} public void Configure(ILoggerFactory loggerFactory)
{
loggerFactory.AddProvider(new MyLoggerProvider()); public ILogger CreateLogger(string categoryName)
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Logging;
using System.Linq;
using System;
namespace Tests
{
public class MyLoggerProvider : ILoggerProvider
{
private static readonly string[] _categories =
{
typeof(RelationalCommandBuilderFactory).FullName,
typeof(SqlServerConnection).FullName
};
public ILogger CreateLogger(string categoryName)
{
if (_categories.Contains(categoryName))
{
return new MyLogger();
}
return NullLogger.Instance;
} using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
namespace EFLogging
{
public class BloggingContextWithFiltering : DbContext
{
// It is very important that applications do not create a new ILoggerFactory instance for each context instance.
// Doing so will result in a memory leak and poor performance.
public static readonly LoggerFactory MyLoggerFactory
= new LoggerFactory(new[]
{
new ConsoleLoggerProvider((category, level)
=> category == DbLoggerCategory.Database.Command.Name
&& level == LogLevel.Information, true)
});
public DbSet<Blog> Blogs { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseLoggerFactory(MyLoggerFactory) // Warning: Do not create a new ILoggerFactory instance each time
.UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=EFLogging;Trusted_Connection=True;ConnectRetryCount=0");
}
} public class BloggingContext : DbContext
{
public BloggingContext()
{ }
public BloggingContext(DbContextOptions options)
: base(options)
{ }
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.EnableSensitiveDataLogging();
optionsBuilder.UseSqlServer(@"...");
optionsBuilder.ConfigureWarnings(warnings =>
{
warnings.Log(CoreEventId.IncludeIgnoredWarning);
warnings.Log(RelationalEventId.QueryClientEvaluationWarning);
});
optionsBuilder.UseLoggerFactory(GetLoggerFactory());
}
}
private ILoggerFactory GetLoggerFactory()
{
IServiceCollection serviceCollection = new ServiceCollection();
serviceCollection.AddLogging(builder =>
builder.AddConsole()
//.AddFilter(category: DbLoggerCategory.Database.Command.Name, level: LogLevel.Information));
.AddFilter(level => true)); // log everything
return serviceCollection.BuildServiceProvider().GetRequiredService<ILoggerFactory>();
}
} Microsoft.EntityFrameworkCore.Database.Command[20101] Executed DbCommand (41ms) [Parameters=[@__id_0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30'] SELECT TOP(2) [m].[Id], [m].[Address], [m].[City], [m].[Email], [m].[Name], [m].[Phone], [m].[PostalCode], [m].[State] FROM [Contact] AS [m] WHERE [m].[Id] = @__id_0
services.AddDbContext<ContactsContext>(options => {
options.UseSqlServer(Configuration["Data:ContactsContext:ConnectionString"]);
options.EnableSensitiveDataLogging();
}); Microsoft.EntityFrameworkCore.Database.Command[20100] Executing DbCommand [Parameters=[@__id_0='1' (Nullable = true)], CommandType='Text', CommandTimeout='30'] SELECT TOP(2) [m].[Id], [m].[Address], [m].[City], [m].[Email], [m].[Name], [m].[Phone], [m].[PostalCode], [m].[State] FROM [Contact] AS [m] WHERE [m].[Id] = @__id_0
var orders =
(from b in context.Orders.TagWith(@"List of top 10 orders")
orderby b.Price descending
select b).Take(10).ToList(); -- List of top 10 orders SELECT TOP(@__p_1) [b].[Id], [b].[Name], [b].[Price] FROM [Orders] AS [b] ORDER BY [b].[Price] DESC
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder
.UseSqlServer(connectionString)
.ConfigureWarnings(c => c.Log((RelationalEventId.CommandExecuting, LogLevel.Info))); var sql = ctx.Artists.Where(a => a.Name == "name 1").ToQueryString();
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.LogTo(Console.WriteLine); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
=> optionsBuilder.LogTo(message => Console.WriteLine(message));