升级到 .NET 6 后 DbContext 出错
Error with DbContext after upgrading to .NET 6
我有一个 ASP.NET Core 3.1 MVC Web 应用程序,我在 these instructions.
之后将其升级到 .NET 6
我所有的单元测试都通过了。
当我 运行 应用程序时,一些查询正在运行,一些查询失败并出现此错误:
An error occurred while writing to logger(s). (The ConnectionString property has not been initialized.)'
我接受了一个失败的查询并将其放入沙盒单元测试中,然后 运行 它。 运行没问题。所以 DbContext
.
的依赖注入有问题
我尝试删除所有 obj
和 bin
文件夹,重新启动 Visual Studio,重新启动我的计算机,none 有帮助。
这是我注册 DbContext
的方式:
var myConnectionString = configuration.GetConnectionString(nameof(MyDbContext));
services.AddDbContext<MyDbContext>(builder =>
{
builder.UseSqlServer(myConnectionString);
});
应用在升级前运行良好。
我该如何解决这个问题?
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 位)17.1.0
详细信息都在堆栈跟踪中。诀窍是知道如何阅读它。
首先例外Message
Message=An error occurred while writing to logger(s). (The ConnectionString property has not been initialized.)
所以您正在尝试将某些内容记录到数据库中,但是没有连接字符串。如果你解决了这个问题,诊断未来的错误会容易得多。
但是什么叫 .Log
触发了这个?
...
at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition.Log[TLoggerCategory](IDiagnosticsLogger`1 logger, Exception exception)
at Microsoft.EntityFrameworkCore.Diagnostics.CoreLoggerExtensions.RowLimitingOperationWithoutOrderByWarning(IDiagnosticsLogger`1 diagnostics)
...
值得庆幸的是,EF Core 团队编写了一个辅助方法来记录/忽略/抛出各种诊断消息,该方法将错误放在方法名称中。快速 google 搜索方法名称会导致 this issue,这应该有助于解决问题的根本原因。
就我个人而言,我会将所有诊断配置为投入调试版本。然后,当您理解每个错误的含义时,禁用那些您认为合适的警告。
.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)
);
我有一个 ASP.NET Core 3.1 MVC Web 应用程序,我在 these instructions.
之后将其升级到 .NET 6我所有的单元测试都通过了。
当我 运行 应用程序时,一些查询正在运行,一些查询失败并出现此错误:
An error occurred while writing to logger(s). (The ConnectionString property has not been initialized.)'
我接受了一个失败的查询并将其放入沙盒单元测试中,然后 运行 它。 运行没问题。所以 DbContext
.
我尝试删除所有 obj
和 bin
文件夹,重新启动 Visual Studio,重新启动我的计算机,none 有帮助。
这是我注册 DbContext
的方式:
var myConnectionString = configuration.GetConnectionString(nameof(MyDbContext));
services.AddDbContext<MyDbContext>(builder =>
{
builder.UseSqlServer(myConnectionString);
});
应用在升级前运行良好。
我该如何解决这个问题?
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 位)17.1.0
详细信息都在堆栈跟踪中。诀窍是知道如何阅读它。
首先例外Message
Message=An error occurred while writing to logger(s). (The ConnectionString property has not been initialized.)
所以您正在尝试将某些内容记录到数据库中,但是没有连接字符串。如果你解决了这个问题,诊断未来的错误会容易得多。
但是什么叫 .Log
触发了这个?
...
at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition.Log[TLoggerCategory](IDiagnosticsLogger`1 logger, Exception exception)
at Microsoft.EntityFrameworkCore.Diagnostics.CoreLoggerExtensions.RowLimitingOperationWithoutOrderByWarning(IDiagnosticsLogger`1 diagnostics)
...
值得庆幸的是,EF Core 团队编写了一个辅助方法来记录/忽略/抛出各种诊断消息,该方法将错误放在方法名称中。快速 google 搜索方法名称会导致 this issue,这应该有助于解决问题的根本原因。
就我个人而言,我会将所有诊断配置为投入调试版本。然后,当您理解每个错误的含义时,禁用那些您认为合适的警告。
.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)
);