0
我有這樣的代碼做承諾錯誤而插入重複記錄
public RetornoDTO Commit(EfDbContext _context)
{
string erroValidation = String.Empty;
try
{
_context.SaveChanges();
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
var erro =
string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
Logger.GetInstance().Erro(erro);
foreach (var ve in eve.ValidationErrors)
{
erroValidation = string.Format("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
Logger.GetInstance().Erro(erroValidation);
}
}
return new RetornoDTO
{
Sucesso = false,
Mensagem = "Error - Erro " + erroValidation
};
}
return new RetornoDTO { Sucesso = true, Mensagem = "Changes saved!!!" };
}
但是,當我嘗試插入重複記錄catch語句不工作,我收到此錯誤:
Cannot insert duplicate key row in object 'dbo.ClienteDoCliente' with unique index 'IX_NomeClienteDoCliente'.The duplicate key value is (Cliente Name Test). The statement has been terminated.
Linha 30: try
Linha 31: {
Linha 32: _context.SaveChanges();
Linha 33: }
Linha 34: catch (DbEntityValidationException e)
我需要改變以避免此消息?
您正在嘗試保存具有唯一約束的數據。更改插入的數據 –
是的,我希望代碼不會顯示堆棧錯誤,但會自定義錯誤並將錯誤記錄到數據庫中。 – b3r3ch1t