我目前正在努力解决一个简单的 SQL 问题,我似乎无法使用“纯”Entity Framework Core 2.2 解决该问题。
如果不执行以下操作,如何在插入期间检查实体是否已存在?
var entity = await _repository.Get(message.Id);
if(entity == null)
{
entity = new Entity ();
// do something with the entity
await _repository.AddAsync(entity);
}
else
{
// do something with the entity
await _repository.Update(entity);
}
await _repository.SaveChangesAsync();
这不够安全。我经常遇到违反主键的情况。我的服务在多个实例上运行,我在短时间内收到具有相同主键的消息。
有没有更好更安全的方法来检查实体是否已经存在于 Entity Framework Core 中而无需自己编写 SQL?
最佳答案
目前 EF Core 本身不支持 Upsert(在此处打开 GitHub 问题:https://github.com/aspnet/EntityFrameworkCore/issues/4526#issuecomment-366818031)
可在此处找到扩展 EF Core 以支持此功能的开源库:https://github.com/artiomchi/FlexLabs.Upsert
关于c# - Entity Framework Core – “Insert if not exists” 可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55157346/