3 回答

TA貢獻1864條經驗 獲得超2個贊
您看到的問題是因為您嘗試插入一個具有重復 ID 的實體但失敗了。重試時,您正在創建第二個實體并嘗試插入它。第一個實體仍與上下文相關聯,并且仍將嘗試保存。在保存新替換或更新現有實體之前,您需要將其與上下文分離。(以下)
hawb = "0402135505536";
var entity = new HawbAsset { HAWB = hawb, HawbStatus = "Allocated", AllocatedDateTime = DateTime.Now, AllocationReference = reference };
while (!uniqueHawb) //insert new hawb
{
//hawb = $"{DateTime.Now:MMddHHmmss}{RandomHelper.GetRandomNumber(0, 999):000}";
try
{
_repository.Insert(entity);
uniqueHawb = true;
}
catch (Exception e)
{
;
}
entity.HAWB = $"{DateTime.Now:MMddHHmmss}{RandomHelper.GetRandomNumber(0, 999):000}";
}
要分離您需要使用的實體,context.Entity(entity).State = EntityState.Detached; 它需要通過您的存儲庫邊界進行操作。
理想情況下,最好在嘗試插入之前檢查 HAWB 的唯一性,但仍然處理那些非常非常罕見的情況,即在檢查和保存之間保存條目:
int retryCount = 0
while (retryCount < 5)
{
try
{
bool isUnique = false;
string hawb = null;
while(!isUnique)
{
hawb = generateHawb();
isUnique = context.HawbAssets.Any(x => x.HAWB == hawb);
}
entity.HAWB = hawb; // this hawb should be unique, so set and insert.
_repository.Insert(entity);
}
catch(UpdateException)
{
// log that this has happened, check inner exception for duplicate key and retry, though limit retry attempts if there are deeper issues that might lock up the system in a retry loop.
retryCount++;
}
}

TA貢獻1829條經驗 獲得超9個贊
它的 1 行額外代碼用于檢查實體是否存在。先做這件事,不要依賴錯誤處理來完成工作:
if ( _repository.HAWBAssets.FirstOrDefault(i => i.HAWB == hawb)== null)
{
_repository.Insert(entity);
uniqueHawb = true;
}

TA貢獻1796條經驗 獲得超10個贊
也許您可以使用納秒來使記錄之間的距離變大,以減少重復的可能性
entity.HAWB = $"{DateTime.Now.Ticks}";
// 636898603227146583
DateTime.Ticks分辨率為 100 納秒
- 3 回答
- 0 關注
- 155 瀏覽
添加回答
舉報