-
Notifications
You must be signed in to change notification settings - Fork 56
Version320 Capture EF Core logging
It is sometimes useful for capture the logging output of EF Core, maybe to see how EF Core translates your query to SQL or how it would create your database. This is done via one of the Sqlite/SqlServer options methods ending in ...WithLogging.
NOTE: The methods shown here are new in version 1.6.0 of the library. The older SetupLogging
is now obsolete as the new version doesn't have the 'bleed' problem that the SetupLogging
method has.
Here is an example for capturing the logging into a list so that you can check the SQL it EF Core is outputting.
[Fact]
public void TestEfCoreLoggingCheckSqlOutput()
{
//SETUP
var logs = new List<LogOutput>();
var options = SqliteInMemory.CreateOptionsWithLogging<BookContext>(
log => logs.Add(log));
using (var context = new BookContext(options))
{
context.Database.EnsureCreated();
//ATTEMPT
context.Books.Count();
//VERIFY
logs.Last().Message.ShouldEndWith(
"SELECT COUNT(*)\r\nFROM \"Books\" AS \"p\"\r\nWHERE \"p\".\"SoftDeleted\" = 0");
}
}
The typical output is to the unit test output window using xUnit's ITestOutputHelper output interface. Here is an example that outputs the SQL that EF Core uses for creating a new SQL Server database. The the Ef Core logs appear to the unit test window (Test Explorer->Output, Resharper->Output window).
[RunnableInDebugOnly]
public void CaptureSqlEfCoreCreatesDatabaseToConsole()
{
//SETUP
var options = this.CreateUniqueClassOptionsWithLogging<BookContext>(
log => _output.WriteLine(log.Message));
using (var context = new BookContext(options))
{
//ATTEMPT
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
}
}
See the class LogOutput for information on various parts of the log.
- Testing against a PostgreSQL db
- Changes in EfCore.TestSupport 5
- Testing with production data
- Using an in-memory database (old)