-
引入Oracle.EntityFrameworkCore
-
添加Model
[Table("T_SYS_USER")]
public class User
{
[Key]
public string USER_ID { get; set; }
}
- 添加上下文
public class SchemeContext : DbContext
{
public SchemeContext() : base()
{
}
public SchemeContext(DbContextOptions options) : base(options)
{
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
//项目中改为从配置中读取数据库连接字符串
optionsBuilder.UseOracle("Data Source=(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.0.1)(PORT = 1521)))(CONNECT_DATA =(SERVER = DEDICATED)(SERVICE_NAME = Test)));User ID=test;Password=test;", f => f.UseOracleSQLCompatibility("12"));
//日志
var loggerFactory = new LoggerFactory();
loggerFactory.AddProvider(new EFLoggerProvider());
optionsBuilder.UseLoggerFactory(loggerFactory);
base.OnConfiguring(optionsBuilder);
}
//public DbSet<UserTable> UserTable { get; set; }
public DbSet<User> User { get; set; }
}
- 日志
public class EFLogger : ILogger
{
private readonly string categoryName;
public EFLogger(string categoryName) => this.categoryName = categoryName;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
//ef core执行数据库查询时的categoryName为Microsoft.EntityFrameworkCore.Database.Command,日志级别为Information
//if (categoryName == "Microsoft.EntityFrameworkCore.Database.Command"
// && logLevel == LogLevel.Information)
//{
var logContent = formatter(state, exception);
//Console.WriteLine();
//Console.ForegroundColor = ConsoleColor.Green;
//Console.WriteLine(logContent);
//Console.ResetColor();
Trace.WriteLine(logContent);
//}
}
public IDisposable BeginScope<TState>(TState state) => null;
}
public class EFLoggerProvider : ILoggerProvider
{
public ILogger CreateLogger(string categoryName) => new EFLogger(categoryName);
public void Dispose() { }
}