【发布时间】:2023-03-03 09:32:20
【问题描述】:
当具有 Id 的条目已经存在时,我正在尝试使用 Entity Framework Core(带有 ASP .NET Core 的 C#)来更新数据库 (PostgreSQL) 中的条目,但这不起作用:
public async Task SaveFileInfos(FileInfo fileInfo)
{
var foundFileInfo = _context.FileInfos.Where(f => f.FileId ==fileInfo.FileId).FirstOrDefault();
if (foundFileInfo == null)
{
await _context.FileInfos.AddAsync(fileInfo);
}
else
{
_context.FileInfos.Update(fileInfo);
}
await _context.SaveChangesAsync();
}
顺便说一下,ID 不能是 GUID,因为它必须是 34 位数字。
public class FileInfo : IFileInfo
{
[Key]
public string FileId { get; set; }
public string FileName { get; set; }
}
如果我想更改已包含的条目,则会出现以下异常:
System.InvalidOperationException: The instance of entity type 'FileInfo' cannot be tracked because another instance with the same key value for {'FileId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.ThrowIdentityConflict(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap`1.Add(TKey key, InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NullableKeyIdentityMap`1.Add(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges, Boolean modifyProperties)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState entityState, Boolean acceptChanges, Boolean modifyProperties, Nullable`1 forceStateWhenUnknownKey)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode`1 node)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode`1 node, Func`2 handleNode)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.AttachGraph(InternalEntityEntry rootEntry, EntityState targetState, EntityState storeGeneratedWithKeySetTargetState, Boolean forceStateWhenUnknownKey)
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.SetEntityState(InternalEntityEntry entry, EntityState entityState)
at Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1.Update(TEntity entity)
我做错了什么?这一定是初学者的错误;-)
【问题讨论】:
标签: c# postgresql asp.net-core entity-framework-core