gpt4 book ai didi

c# - Entity Framework Core 5 在 SaveChanges() 中抛出 System.FormatException

转载 作者:行者123 更新时间:2023-12-03 01:22:56 27 4
gpt4 key购买 nike

我目前正在开发 ASP.NET Core 5.0 应用程序 - 我尝试将该应用程序从 SqLite DB 提供程序迁移到 CosmosDb。我使用 Entity Framework Core

  • “Microsoft.EntityFrameworkCore”版本=“5.0.7”
  • “Microsoft.EntityFrameworkCore.Cosmos”版本=“5.0.7”

我使用“Azure Cosmos DB 模拟器”或“真正的 azure 数据库实例”,没有区别。执行 .SaveChanges() 时,Visual Studio 2019 输出窗口中有日志行:

抛出异常:

'System.FormatException' in System.Private.CoreLib.dll
Exception: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters.

  • 我的实体仍然被写入数据库!但这似乎会影响性能。

我创建了一个文件单元测试项目来演示:

    using Microsoft.EntityFrameworkCore;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.ComponentModel.DataAnnotations;
using System.Diagnostics;
using System.Threading.Tasks;

namespace UnitTestCosmos
{
[TestClass]
public class UnitTestCosmosDb
{
[TestMethod]
public async Task TryWriteDataAsync()
{
using (var destinationcontext = new MyDbContext())
{
var item = new MyVerbrauch(){MessId = Guid.NewGuid(), StromHausKwh = 357};
Debug.WriteLine($"Try Write ");
try
{
await destinationcontext.MyVerbrauch.AddAsync(item);
Debug.WriteLine($"\nSave to MyDbContext\n");

await destinationcontext.SaveChangesAsync(); // throws ??
}
catch (Exception ex)
{
Debug.WriteLine($"Exception: {ex.Message}");
}
}
}
}

public class MyVerbrauch
{
[Key]
[Required]
public Guid MessId { get; set; }

[Required]
public int StromHausKwh { get; set; }
}

public class MyDbContext : DbContext
{
public DbSet<MyVerbrauch> MyVerbrauch { get; set; }

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
// Use Cosmos DB
optionsBuilder.UseCosmos("https://localhost:8081",
"< your key>",
databaseName: "CosmosDBdemo.cdb");
}
}
}

这是我关于堆栈溢出的第一个问题,我将不胜感激任何帮助!!

7 月 15 日添加:

Visual Studio 输出窗口:

    Save to  MyDbContext

'testhost.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.7\System.Net.Security.dll'. Symbols loaded.
'testhost.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.7\System.Security.Cryptography.X509Certificates.dll'. Symbols loaded.
'testhost.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.7\System.Security.Cryptography.Primitives.dll'. Symbols loaded.
'testhost.exe' (CoreCLR: clrhost): Loaded 'E:\Andreas\git\CosmosDbTest\CosmosDbTest\bin\Debug\net5.0\System.Configuration.ConfigurationManager.dll'. Symbols loaded.
'testhost.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.7\System.Net.WebClient.dll'. Symbols loaded.
'testhost.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.7\System.Net.ServicePoint.dll'. Symbols loaded.
'testhost.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.7\System.Buffers.dll'.
DocDBTrace Information: 0 : DocumentClient with id 1 initialized at endpoint: https://localhost:8081/ with ConnectionMode: Direct, connection Protocol: Tcp, and consistency level: null
'testhost.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.7\System.Collections.NonGeneric.dll'. Symbols loaded.
'testhost.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.7\System.Security.Principal.Windows.dll'. Symbols loaded.
'testhost.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.7\System.Security.Claims.dll'. Symbols loaded.
'testhost.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\5.0.7\System.Security.Cryptography.Encoding.dll'. Symbols loaded.
DocDBTrace Information: 0 : RefreshLocationAsync() refreshing locations
DocDBTrace Information: 0 : Current WriteEndpoints = (https://127.0.0.1:8081/) ReadEndpoints = (https://127.0.0.1:8081/)
DocDBTrace Information: 0 : TimerPool Created with minSupportedTimerDelayInSeconds = 1
DocDBTrace Information: 0 : RntbdConnectionDispenser: requestTimeoutInSeconds: 10, openTimeoutInSeconds: 5, timerValueInSeconds: 1
DocDBTrace Information: 0 : Creating RNTBD TransportClient with options Rntbd.TransportClient.Options
OpenTimeout: 00:00:05
RequestTimeout: 00:00:10
TimerPoolResolution: 00:00:01
MaxChannels: 65535
PartitionCount: 1
MaxRequestsPerChannel: 30
ReceiveHangDetectionTime: 00:01:05
SendHangDetectionTime: 00:00:10
IdleTimeout: -00:00:01
EnableCpuMonitor: True
UserAgent: cosmos-netstandard-sdk/3.12.0|3.11.4|01|X64|Microsoft Windows 10.0.19041|.NET 5.0.7| Microsoft.EntityFrameworkCore.Cosmos/5.0.7 Suffix: Microsoft.EntityFrameworkCore.Cosmos/5.0.7
CertificateHostNameOverride:

DocDBTrace Information: 0 : TimerPool Created with minSupportedTimerDelayInSeconds = 1
DocDBTrace Information: 0 : CpuMonitor started
The thread 0x44c4 has exited with code 0 (0x0).
Exception thrown: 'System.FormatException' in System.Private.CoreLib.dll
DocDBTrace Information: 0 : CpuMonitor started
The thread 0x1f2c has exited with code 0 (0x0).
Exception thrown: 'System.FormatException' in System.Private.CoreLib.dll
DocDBTrace Information: 0 : Opened 1 channels to server rntbd://127.0.0.1:10253/
DocDBTrace Information: 0 : Awaiting RNTBD channel initialization. Request URI: rntbd://127.0.0.1:10253/apps/DocDbApp/services/DocDbServer20/partitions/a4cb4960-38c8-11e6-8106-8cdcd42c33be/replicas/1p/
DocDBTrace Information: 0 : RNTBD: ConnectUnicastPortAsync connecting to rntbd://127.0.0.1:10253/ (address 127.0.0.1)
DocDBTrace Information: 0 : RNTBD connection established 127.0.0.1:51807 -> 127.0.0.1:10253
DocDBTrace Information: 0 : RNTBD SSL handshake complete 127.0.0.1:51807 -> 127.0.0.1:10253
The thread 0x27cc has exited with code 0 (0x0).
The thread 0x1904 has exited with code 0 (0x0).
The program '[17280] testhost.exe' has exited with code 0 (0x0).

和调用堆栈

    System.Private.CoreLib.dll!System.Convert.FromBase64CharPtr(char* inputPtr, int inputLength) Line 2776  C#
System.Private.CoreLib.dll!System.Convert.FromBase64String(string s) Line 2568 C#
Microsoft.Azure.Cosmos.Direct.dll!Microsoft.Azure.Documents.ResourceId.FromBase64String(string s) Unknown
Microsoft.Azure.Cosmos.Direct.dll!Microsoft.Azure.Documents.ResourceId.Verify(string id, out byte[] buffer) Unknown
Microsoft.Azure.Cosmos.Direct.dll!Microsoft.Azure.Documents.ResourceId.TryParse(string id, out Microsoft.Azure.Documents.ResourceId rid) Unknown
Microsoft.Azure.Cosmos.Direct.dll!Microsoft.Azure.Documents.PathsHelper.TryParsePathSegmentsWithDatabaseAndCollectionNames(string resourceUrl, out bool isFeed, out string resourcePath, out string resourceIdOrFullName, out bool isNameBased, out string databaseName, out string collectionName, string clientVersion, bool parseDatabaseAndCollectionNames) Unknown
Microsoft.Azure.Cosmos.Direct.dll!Microsoft.Azure.Documents.DocumentServiceRequest.DocumentServiceRequest(Microsoft.Azure.Documents.OperationType operationType, Microsoft.Azure.Documents.ResourceType resourceType, string path, System.IO.Stream body, Microsoft.Azure.Documents.AuthorizationTokenType authorizationTokenType, Microsoft.Azure.Documents.Collections.INameValueCollection headers) Unknown
Microsoft.Azure.Cosmos.Direct.dll!Microsoft.Azure.Documents.DocumentServiceRequest.Create(Microsoft.Azure.Documents.OperationType operationType, Microsoft.Azure.Documents.ResourceType resourceType, string relativePath, Microsoft.Azure.Documents.AuthorizationTokenType authorizationTokenType, Microsoft.Azure.Documents.Collections.INameValueCollection headers) Unknown
Microsoft.Azure.Cosmos.Client.dll!Microsoft.Azure.Cosmos.Routing.ClientCollectionCache.ReadCollectionAsync(string collectionLink, System.Threading.CancellationToken cancellationToken, Microsoft.Azure.Cosmos.IDocumentClientRetryPolicy retryPolicyInstance) Line 61 C#
Microsoft.Azure.Cosmos.Client.dll!Microsoft.Azure.Cosmos.Routing.ClientCollectionCache.GetByNameAsync.AnonymousMethod__0() Line 52 C#
Microsoft.Azure.Cosmos.Client.dll!Microsoft.Azure.Cosmos.TaskHelper.InlineIfPossible.AnonymousMethod__0() Line 67 C#
Microsoft.Azure.Cosmos.Direct.dll!Microsoft.Azure.Documents.BackoffRetryUtility<System.__Canon>.ExecuteAsync.AnonymousMethod__0() Unknown
Microsoft.Azure.Cosmos.Direct.dll!Microsoft.Azure.Documents.BackoffRetryUtility<Microsoft.Azure.Cosmos.ContainerProperties>.ExecuteRetryAsync(System.Func<System.Threading.Tasks.Task<Microsoft.Azure.Cosmos.ContainerProperties>> callbackMethod, System.Func<System.Exception, System.Threading.CancellationToken, System.Threading.Tasks.Task<Microsoft.Azure.Documents.ShouldRetryResult>> callShouldRetry, System.Func<System.Threading.Tasks.Task<Microsoft.Azure.Cosmos.ContainerProperties>> inBackoffAlternateCallbackMethod, System.TimeSpan minBackoffForInBackoffCallback, System.Threading.CancellationToken cancellationToken, System.Action<System.Exception> preRetryCallback) Unknown
Microsoft.Azure.Cosmos.Direct.dll!Microsoft.Azure.Documents.BackoffRetryUtility<Microsoft.Azure.Cosmos.ContainerProperties>.ExecuteAsync(System.Func<System.Threading.Tasks.Task<Microsoft.Azure.Cosmos.ContainerProperties>> callbackMethod, Microsoft.Azure.Documents.IRetryPolicy retryPolicy, System.Threading.CancellationToken cancellationToken, System.Action<System.Exception> preRetryCallback) Unknown
Microsoft.Azure.Cosmos.Client.dll!Microsoft.Azure.Cosmos.TaskHelper.InlineIfPossible<Microsoft.Azure.Cosmos.ContainerProperties>(System.Func<System.Threading.Tasks.Task<Microsoft.Azure.Cosmos.ContainerProperties>> function, Microsoft.Azure.Documents.IRetryPolicy retryPolicy, System.Threading.CancellationToken cancellationToken) Line 80 C#
Microsoft.Azure.Cosmos.Client.dll!Microsoft.Azure.Cosmos.Routing.ClientCollectionCache.GetByNameAsync(string apiVersion, string resourceAddress, System.Threading.CancellationToken cancellationToken) Line 51 C#
Microsoft.Azure.Cosmos.Client.dll!Microsoft.Azure.Cosmos.Common.CollectionCache.ResolveByNameAsync.AnonymousMethod__0() Line 253 C#
System.Private.CoreLib.dll!System.Threading.Tasks.Task<System.Threading.Tasks.Task<Microsoft.Azure.Cosmos.ContainerProperties>>.InnerInvoke() Line 497 C#
System.Private.CoreLib.dll!System.Threading.Tasks.Task..cctor.AnonymousMethod__277_0(object obj) Line 2359 C#
System.Private.CoreLib.dll!System.Threading.ExecutionContext.RunFromThreadPoolDispatchLoop(System.Threading.Thread threadPoolThread, System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) Line 274 C#
System.Private.CoreLib.dll!System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref System.Threading.Tasks.Task currentTaskSlot, System.Threading.Thread threadPoolThread) Line 2320 C#
System.Private.CoreLib.dll!System.Threading.Tasks.Task.ExecuteEntryUnsafe(System.Threading.Thread threadPoolThread) Line 2258 C#
System.Private.CoreLib.dll!System.Threading.Tasks.Task.ExecuteFromThreadPool(System.Threading.Thread threadPoolThread) Line 2243 C#
System.Private.CoreLib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() Line 641 C#
System.Private.CoreLib.dll!System.Threading._ThreadPoolWaitCallback.PerformWaitCallback() Line 29 C#

最佳答案

我使用 CosmosDB(云)和 Cosmos DB 模拟器验证了上面评论中给出的结果。该问题是由选择的数据库名称引起的(它被设置为“CosmosDBdemo.cdb”)

尝试在“Microsoft.Azure.Documents.ResourceId.FromBase64String(string s)”中对该字符串进行 Base64 解码并引发异常。更改databaseName时不再出现异常。

解决方案似乎是:永远不要使用“.”在数据库名称中

关于c# - Entity Framework Core 5 在 SaveChanges() 中抛出 System.FormatException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68384790/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com