[英]Entity Framwork Core – Is a “Insert if not exists” possible?
我目前正在努力解決一個簡單的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();
這還不夠安全。 我不斷收到主鍵沖突。 我的服務在多個實例上運行,並且在短時間內收到具有相同主鍵的消息。
是否有更好,更安全的方法來檢查實體框架核心中是否已經存在一個實體,而無需自己編寫SQL?
當前,EF Core本身不支持Upsert(在此處打開GitHub問題: https : //github.com/aspnet/EntityFrameworkCore/issues/4526#issuecomment-366818031 )
可在此處找到擴展EF Core以支持此功能的開源庫: https : //github.com/artiomchi/FlexLabs.Upsert
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.