程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了Entity Framework Core 5 在 SaveChanges()大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决Entity Framework Core 5 在 SaveChanges()?

开发过程中遇到Entity Framework Core 5 在 SaveChanges()的问题如何解决?下面主要结合日常开发的经验,给出你关于Entity Framework Core 5 在 SaveChanges()的解决方法建议,希望对你解决Entity Framework Core 5 在 SaveChanges()有所启发或帮助;

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

  • "Microsoft.EntityFrameworkCore" Version="5.0.7"
  • "Microsoft.EntityFrameworkCore.Cosmos" Version="5.0.7"

使用“Azure Cosmos DB Emulator”或“真正的 azure db 实例”,没有任何区别。执行 .SaveChanges() 时,Visual studio 2019 输出窗口中有日志行:

抛出异常

System.Private.Corelib.dll 中的“System.FormatException”
例外:输入不是有效的 Base-64 字符串,因为它包含非 Base-64 字符、两个以上的填充字符或填充字符中的非法字符。

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

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

    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 @R_695_6756@ (0x0).
    Exception thrown: 'System.FormatException' in System.Private.Corelib.dll
    DocDBTrace information: 0 : cpuMonitor started
    The thread 0x1f2c has exited with @R_695_6756@ (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 @R_695_6756@ (0x0).
    The thread 0x1904 has exited with @R_695_6756@ (0x0).
    The program '[17280] testhost.exe' has exited with @R_695_6756@ (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,String relativePath,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.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.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,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 时不再发生异常。

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

大佬总结

以上是大佬教程为你收集整理的Entity Framework Core 5 在 SaveChanges()全部内容,希望文章能够帮你解决Entity Framework Core 5 在 SaveChanges()所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。