如何确切地知道哪个字段引发了DbUpdateException

时间:2013-07-22 21:32:36

标签: asp.net-mvc entity-framework

我有以下Action方法,目前模型类有两个在数据库中设置为Unique的属性(Name& IP)。因此,如果用户尝试添加/编辑记录,并且他提供了已存在的IP或名称,则将引发以下异常DbUpdateException.

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(ServerToEdit serverToEdit)
        {
            try
            {
               if (ModelState.IsValid)
           {
                repository.InsertOrUpdateServer(serverToEdit.Server,serverToEdit.TechnologyIP);
                repository.Save();
                return RedirectToAction("Index");
            }

               else
               {

                return View(serverToEdit);
           }
           }
           catch ()
           {
               ModelState.AddModelError(string.Empty, "Error occured. The Same IP/Name might already assinged.");

               return View(serverToEdit);


           }
           catch (DbEntityValidationException)
           {
               ModelState.AddModelError(string.Empty, "Error occured. User might not be defiend inside Active Directory.");

               return View(serverToEdit);
           }

            return null;

我正在显示IP或名称可能已经存在的一般消息,那么有没有办法知道哪个字段引发了错误,并向用户显示了更具体的错误消息?

2 个答案:

答案 0 :(得分:-1)

您可以创建此扩展程序:

public static class DbUpdateExceptionExtension
{
    public static bool ViolateConstraint(this DbUpdateException e, string fieldName)
    {
        return e.InnerException.InnerException.Message.Contains(fieldName);
    }
}

然后如果你有这样的约束:

ALTER TABLE [Account]  ADD CONSTRAINT UniqueLogin  UNIQUE([Login])

你可以这样做:

try
{
    await databaseContext.SaveChangesAsync();
    return RedirectToAction("Index");
}
catch (DbUpdateException e)
{
    if (e.ViolateConstraint("UniqueLogin"))
        ModelState.AddModelError("Login", "Nom d'utilisateur ou mot de passe non valide.");
}

HF GL!

答案 1 :(得分:-2)

是, 您可以调用 Context.ValidateEntity

DbEntityValidationResult包含问题。在里面你会看到ICollection<DbValidationError> ValidationErrors

 public string PropertyName { get; }
 public string ErrorMessage { get; }
相关问题