c# - 升级到 .NET 6 后 DbContext 出现错误

标签 c# entity-framework .net-6.0

我有一个 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.)'

enter image description here

我采取了其中一个失败的查询并将其放入沙盒单元测试中并运行它。它运行良好。所以DbContext的依赖注入(inject)有问题。

我尝试删除所有 objbin 文件夹,重新启动 Visual Studio,重新启动我的计算机,但都没有帮助。

以下是我注册 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=An error occurred while writing to logger(s). (The ConnectionString property has not been initialized.)  

因此,您正在尝试将某些内容记录到数据库中,但没有连接字符串。如果解决了这个问题,诊断 future 的错误将会容易得多。

但是什么叫.Log来触发这个呢?

...
       at Microsoft.EntityFrameworkCore.Diagnostics.EventDefinition.Log[TLoggerCategory](IDiagnosticsLogger`1 logger, Exception exception)
       at Microsoft.EntityFrameworkCore.Diagnostics.CoreLoggerExtensions.RowLimitingOperationWithoutOrderByWarning(IDiagnosticsLogger`1 diagnostics)
...

值得庆幸的是,EF Core 团队编写了一个辅助方法来记录/忽略/抛出各种诊断消息,该方法将错误放在方法名称中。快速谷歌搜索方法名称会导致 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)
    );

关于c# - 升级到 .NET 6 后 DbContext 出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71401673/

相关文章:

c# - 提取数据的正则表达式

linq - 按日期过滤查询

c# - 从 Razor 类库内部访问 Microsoft.AspNetCore.Components.Server.Circuits

c# - 无平台网络的预处理器符号

c# - 如何使用 .NET 6 的新最小托管模型在集成测试中使 Serilog 静音

C# 属性 : One Attribute to Rule Them All?

c# - 使用 IPP .NET SDK for QuickBooks v3.0 的 SalesItemLineDetail 上没有可用的单价?

c# - 不能将文本数据类型选为 DISTINCT,因为它不可比较

entity-framework - Entity Framework 6 - 启用迁移时不创建表

entity-framework - 如何在 WCF 数据服务中编写 'In' 查询?