[英]Is it faster to try and avoid UNIQUE violations when inserting into a PostgreSQL database with efcore, or to catch the resulting exception?
假設我對 postgresql 數據庫中的列有一個 UNIQUE 約束,在嘗試插入新值之前查詢數據庫的性能是否更高,或者在數據庫拒絕查詢時捕獲拋出的異常是否可以接受?
我的假設是 postgres 將比 EF 核心構建和執行查詢 + 然后運行插入更快地檢查這些違規行為。 是這種情況嗎?
try
{
// _dctx is my DbContext
_dctx.SomeTable.Add(newEntity);
await _dctx.SaveChangesAsync();
}
catch (DbUpdateException ex)
{
if (ex.InnerException is PostgresException npgex && npgex.SqlState == PostgresErrorCodes.UniqueViolation)
{
// Reached only when the UNIQUE constraint was violated
}
throw; // How other exceptions are handled isn't relevant to the question
}
對比
try
{
if (await _dctx.SomeTable.AnyAsync(x => x.UniqueProperty == hopefullyUniquePropertyValue))
{
// Handle duplicate insertion here
}
_dctx.SomeTable.Add(newEntity);
await _dctx.SaveChangesAsync();
}
catch (DbUpdateException ex) {}
由於這將在此服務的多個實例中同時/在此服務的多個實例上完成,因此我仍然希望偶爾獲得這些異常,但問題是AnyAsync()
調用的開銷是否會大大大於允許數據庫的開銷+ ORM 來照顧它?
在插入之前檢查一行是否存在絕對是更糟糕的選擇,原因有兩個:
然而,與其討論理論上的性能,不如簡單地對這兩個選項進行基准測試(使用BenchmarkDotNet 之類的東西)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.