I have an ASP.NET Core 3.1 MVC web application, which I upgraded to .NET 6 following
I took one of the failing queries and put it in a Sandbox Unit Test and ran it. It runs fine. So there is something wrong with the dependency injection of the DbContext
.
I tried deleting all obj
and bin
folders, restarting Visual Studio, restarting my computer, none of which helped.
Here is how I am registering my DbContext
:
var myConnectionString = configuration.GetConnectionString(nameof(MyDbContext));
services.AddDbContext<MyDbContext>(builder =>
{
builder.UseSqlServer(myConnectionString);
});
The app was working fine before the upgrade.
How do I fix this?
System.AggregateException
HResult=0x80131500
Message=An error occurred while writing to logger(s). (The ConnectionString property has not been initialized.)
Source=Microsoft.Extensions.Logging
StackTrace:
at Microsoft.Extensions.Logging.Logger.ThrowLoggingError(List`1 exceptions)
at Microsoft.Extensions.Logging.Logger.Log[TState](LogLevel logLevel, EventId eventId, TState state, Exception exception, Func`3 formatter)
at Microsoft.Extensions.Logging.LoggerMessage.<>c__DisplayClass8_0.<Define>g__Log|0(ILogger logger, Exception exception)
at Microsoft.Extensions.Logging.LoggerMessage.<>c__DisplayClass8_0.<Define>b__1(ILogger logger, Exception exception)
at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition.Log[TLoggerCategory](IDiagnosticsLogger`1 logger, Exception exception)
at Microsoft.EntityFrameworkCore.Diagnostics.CoreLoggerExtensions.RowLimitingOperationWithoutOrderByWarning(IDiagnosticsLogger`1 diagnostics)
at Microsoft.EntityFrameworkCore.Query.RelationalQueryableMethodTranslatingExpressionVisitor.TranslateTake(ShapedQueryExpression source, Expression count)
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.QueryableMethodTranslatingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression)
at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass12_0`1.<ExecuteAsync>b__0()
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.ExecuteAsync[TResult](Expression query, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.ExecuteAsync[TResult](Expression expression, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable`1.GetAsyncEnumerator(CancellationToken cancellationToken)
at System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1.GetAsyncEnumerator()
at Microsoft.EntityFrameworkCore.EntityFrameworkQueryableExtensions.<ToListAsync>d__65`1.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at My.PartnerQueries.<GetIndexViewModel>d__3.MoveNext() in C:\Users\my\source\repos\my\My.Services\Partners\PartnerQueries.cs:line 21
This exception was originally thrown at this call stack:
[External Code]
Inner Exception 1:
InvalidOperationException: The ConnectionString property has not been initialized.
.NET SDK 6.0.200. Visual Studio 2022 (64-bit) 17.1.0
CodePudding user response:
The details are all there in the stack trace. The trick is knowing how to read it.
First the exception Message
Message=An error occurred while writing to logger(s). (The ConnectionString property has not been initialized.)
So you're trying to log something into a database, but there's no connection string. If you fix that, diagnosing future errors is going to be much easier.
But what called .Log
to trigger this?
...
at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition.Log[TLoggerCategory](IDiagnosticsLogger`1 logger, Exception exception)
at Microsoft.EntityFrameworkCore.Diagnostics.CoreLoggerExtensions.RowLimitingOperationWithoutOrderByWarning(IDiagnosticsLogger`1 diagnostics)
...
Thankfully the EF Core team have written a helper method to log / ignore / throw for various diagnostic messages, which puts the error right there in the method name. A quick google search for the method name leads to this issue, which should help to resolve the root cause of the problem.
Personally I would configure all diagnostics to throw in a debug build. Then as you understand what each error means, disable those warnings you are comfortable with.
.UseSqlServer(connectionString, options => { ... })
.ConfigureWarnings(w => w
#if DEBUG
// throw on all EF query diagnostics in debug builds (eg query should be split)
.Default(WarningBehavior.Throw)
#endif
.Log(CoreEventId.RowLimitingOperationWithoutOrderByWarning)
);