[英]EF Core - Insert then update an entry
In a WebApi method I need, if an element not exist, insert it and after a few operations update it. 在WebApi方法中,如果元素不存在,我需要将其插入,并在一些操作后对其进行更新。
The code is the following: 代码如下:
Entry existingEntry = await _repo.GetEntryByIdAsync(id);
existingEntry = await _repo.AddNewEntryAsync(existingAccred);
// Some code...
// Update
existingAccred.IdField = myField;
await _repo.UpdateEntryAsync(existingEntry);
The repo is the following: 仓库如下:
public async Task<Entry> GetEntryByIdAsync(int myId)
{
var result = from entry in _ctx.Set<DALENTRY>()
where entry.ID == myId
select new Entry
{
ID = entry.IdEntry,
};
return await result.AsNoTracking().FirstOrDefaultAsync();
}
public async Task<Entry> AddNewEntryAsync(Entry newEntry)
{
DALENTRY entry = new DALENTRY()
{
GUID = newEntry.GUID,
};
_ctx.Add(entry);
await _ctx.SaveChangesAsync();
newEntry.IdEntry = entry.ID;
return newEntry;
}
public async Task<Entry> UpdateEntryAsync(Entry updateEntry)
{
DALENTRY entry = new DALENTRY()
{
ID = updateEntry.IdEntry,
FIELD= updateEntry.IdField,
};
_ctx.Update(entry);
await _ctx.SaveChangesAsync();
return updateEntry;
}
But when I perform the update I'm getting is the following error: 但是,当我执行更新时,出现以下错误:
An unhandled exception occurred while processing the request. 处理请求时发生未处理的异常。
InvalidOperationException: The instance of entity type 'DALENTRY' cannot be tracked because another instance with the same key value for {'ID'} is already being tracked. InvalidOperationException:无法跟踪实体类型“ DALENTRY”的实例,因为已经跟踪了另一个具有相同“ {'ID'}”键值的实例。 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. 考虑使用'DbContextOptionsBuilder.EnableSensitiveDataLogging'来查看冲突的键值。 Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap.Add(TKey key, InternalEntityEntry entry) Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap.Add(TKey键,InternalEntityEntry条目)
The repo is registered as Transient like: 该仓库被注册为Transient,如:
services.AddTransient<EntryRepository>();
I tried using Detach after the insert, but using it the update is clearing all the non updated fields. 我尝试在插入后使用Detach,但是使用它更新会清除所有未更新的字段。 I can't remember what is causing this issue. 我不记得是什么引起了这个问题。
Solved changing my update strategy in the repo by read the entry first, then update it: 通过先阅读条目,然后更新它,解决了在仓库中更改我的更新策略的问题:
public async Task<Entry> UpdateEntryAsync(Entry updateEntry)
{
DALENTRY entry = await _ctx.Set<DALENTRY >().SingleOrDefaultAsync(a => a.ID == updateEntry.IdEntry);
entry.FIELD= updateEntry.IdField,
_ctx.Update(entry);
await _ctx.SaveChangesAsync();
return updateEntry;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.