Output generated SQL from Entity Framework to the console
dotnet add [project_file.csproj] package Microsoft.Extensions.Logging.Console
public static readonly ILoggerFactory MyLoggerFactory = LoggerFactory.Create(builder => {builder.AddConsole();});
...
services.AddDbContext(o => {
o.UseSqlServer(connection, options => options.EnableRetryOnFailure())
.UseLoggerFactory(MyLoggerFactory);
})
...
DB Context is null when being injected into a Repository class
Fields in appsettings.json must have a correspdoning property in AppSettings.cs in order to be available in code.
Unit Testing Entity Framework connected to SQL Server
var configurationBuilder = new ConfigurationBuilder()
.SetBasePath(AppDomain.CurrentDOmain.BaseDirectory)
.AddJsonFile($"appSettings.json", optional: false, reloadOnChange: false)
.AddEnvironmentVariables().Build();
var services = new ServiceCollection()
.Configure(configurationBuilder)
.AddSingleton(resolver => resolver.GetRequiredService>().Value)
services.AddTransient()
services.AddDbContext(o => {
o.UseSqlServer(contextInstance);
});
From the Unit Test, get the service by calling a method on the fixture after everything has started up.
public T GetService(){
return _provider.GetServices().FirstOrDefault();
}