Cri*_*lho 7 c# sql entity-framework
我需要一种方法来区分使用实体框架LINQ的SQL异常,例如,当我从DbUpdateException获得的是大量嵌套的内部异常和无用的长错误消息时,如何区分出现外键约束违规或唯一约束违规?是否存在任何较低级别的异常,我可以执行类似"Catch FKException"的操作; 捕获"uniqueException"或类似的东西.
Mr.*_*hoo 13
try
{
//code
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
string rs = "";
foreach (var eve in e.EntityValidationErrors)
{
rs = string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State);
Console.WriteLine(rs);
foreach (var ve in eve.ValidationErrors)
{
rs += "<br />" + string.Format("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage);
}
}
throw new Exception(rs);
}
Run Code Online (Sandbox Code Playgroud)
使用sql错误代码......
catch (DbUpdateException ex)
{
var sqlex = ex.InnerException.InnerException as SqlException;
if (sqlex != null)
{
switch (sqlex.Number)
{
case 547: throw new ExNoExisteUsuario("No existe usuario destino."); //FK exception
case 2627:
case 2601:
throw new ExYaExisteConexion("Ya existe la conexion."); //primary key exception
default: throw sqlex; //otra excepcion que no controlo.
}
}
throw ex;
}
Run Code Online (Sandbox Code Playgroud)