Sha*_*iel 6 c# entity-framework entity-framework-core
我目前正在努力解决一个简单的 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();
Run Code Online (Sandbox Code Playgroud)
这还不够安全。我不断收到主键违规。我的服务在多个实例上运行,我在短时间内收到具有相同主键的消息。
是否有更好更安全的方法来检查实体是否已存在于 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
| 归档时间: |
|
| 查看次数: |
4993 次 |
| 最近记录: |