我有以下代码插入一个具有随机生成值“hawb”的实体作为列之一。我的想法是,因为hawb是表中的唯一列,所以 try-catch 块将在插入重复值时捕获异常。工作流程工作正常,直到我开始测试它并出现一些奇怪的错误。
[Code]
hawb = "0402135505536";
while (!uniqueHawb) //insert new hawb
{
//hawb = $"{DateTime.Now:MMddHHmmss}{RandomHelper.GetRandomNumber(0, 999):000}";
var entity = new HawbAsset { HAWB = hawb, HawbStatus = "Allocated", AllocatedDateTime = DateTime.Now, AllocationReference = reference };
try
{
_repository.Insert(entity);
uniqueHawb = true;
}
catch (Exception e)
{
;
}
hawb = $"{DateTime.Now:MMddHHmmss}{RandomHelper.GetRandomNumber(0, 999):000}";
}
[Model]
public class HawbAsset : BaseEntity
{
[Required(AllowEmptyStrings = false)]
[Index(IsUnique = true)]
[StringLength(15)]
public string HAWB { get; set; }
[Required(AllowEmptyStrings = false)]
public string HawbStatus { get; set; }
public DateTime? AllocatedDateTime { get; set; }
[Required(AllowEmptyStrings = false)]
public string AllocationReference { get; set; }
public DateTime? ConfirmedUsageDateTime { get; set; }
public DateTime? RecycledDateTime { get; set; }
public string Owner { get; set; }
}
我硬编码了一个重复值 0402135505536,因此它会在第一时间捕获“重复键异常”,这是预期的。然而,当 hawb 是随机生成的,并且我已经确定值不同时,它仍然会捕获相同的“Duplicate Key Exception”。谁能告诉我发生了什么以及如何实现我的目标?谢谢!
慕斯王
PIPIONE
白衣染霜花
相关分类