Boa tarde Lucas.
Obrigado pela ajuda.
Segue o código da classe Program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace Alura.Loja.Testes.ConsoleApp
{
class Program
{
static void Main(string[] args)
{
using (var contexto = new LojaContext()) {
var produtos = contexto.Produtos.ToList();
var serviceProvider = contexto.GetInfrastructure<IServiceProvider>();
var loggerFactory = serviceProvider.GetService<ILoggerProvider>();
loggerFactory.AddProvider(SqlLoggerProvider.Create());
foreach (var item in produtos) {
Console.WriteLine(item);
}
Console.WriteLine("=================");
foreach (var e in contexto.ChangeTracker.Entries()) {
Console.WriteLine(e.State);
}
var p1 = produtos.First();
p1.Nome = "Harry Potter - Editado";
Console.WriteLine("=================");
foreach (var e in contexto.ChangeTracker.Entries()) {
Console.WriteLine(e.State);
}
contexto.SaveChanges();
Console.WriteLine("=================");
produtos = contexto.Produtos.ToList();
foreach (var p in produtos) {
Console.WriteLine(p);
}
}
}
}
}
Classe SqlLoggerProvider:
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.Extensions.Logging;
using System;
namespace Alura.Loja.Testes.ConsoleApp {
public class SqlLoggerProvider:ILoggerProvider {
public static ILoggerProvider Create() {
return new SqlLoggerProvider();
}
public ILogger CreateLogger(string categoryName) {
if (categoryName == typeof(IRelationalCommandBuilderFactory).FullName) {
return new SqlLogger();
}
return new NullLogger();
}
public void Dispose() {
}
}
internal class NullLogger:ILogger {
public IDisposable BeginScope<TState>(TState state) {
return null;
}
public bool IsEnabled(LogLevel logLevel) {
return true;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) {
//não faz nada
}
}
public class SqlLogger:ILogger {
public IDisposable BeginScope<TState>(TState state) {
return null;
}
public bool IsEnabled(LogLevel logLevel) {
return true;
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) {
Console.WriteLine("");
Console.WriteLine(formatter(state, exception));
Console.WriteLine("");
}
}
}