SaveChanges - 在数据库中创建新对象(错误)

时间:2015-04-05 12:17:55

标签: c# html sql asp.net-mvc-4 razor

我在Visual Studio 2013中有一个MVC4项目,该项目目前是虚构私人飞行公司的一个非常基本的网站。

以下是我的相关文件: https://gist.github.com/anonymous/b744c44dc77084839e6d

我正在尝试为管理员实现一个表单/视图来编辑现有的用户数据库。我已成功完成表单但是在尝试保存到数据库时遇到错误。

编辑:数据库:http://gyazo.com/ff5d077b7f000ee78e372530b237696b

(以下是现有数据库的样子: http://gyazo.com/a088c2cd75779b39bb343eca1aecb219

这就是AdminIndex pov:http://gyazo.com/3a3533d07a96b4116554e0795df81a52

的样子

MyTemplateController(基本上是我的HomeController)中,我有一段代码,负责创建一个新的“人”,如果你愿意的话。

    [HttpPost]
    public ActionResult Create(SystemUser users)
    {
        if (ModelState.IsValid)
        {
            //ss.StudentsTbls.AddObject(student); // Ignore this
            ss.SystemUsers.Add(users);
            ss.SaveChanges();
            return RedirectToAction("AdminIndex");
        }

        return View(users);
    }

这段代码是为了保存用户从AdminIndex -> Create New插入的信息,但是,当我按下创建时,我收到以下错误:http://gyazo.com/fe45ace191af8a6944f39217adb576a5

有人能够指出为什么会这样吗?感谢。

编辑:AdminIndex.cshtml和Create.cshtml https://gist.github.com/anonymous/fbd92ef0b1847efd2408

2 个答案:

答案 0 :(得分:0)

在try catch block中编写代码

 [HttpPost]
    public ActionResult Create(SystemUser users)
    {
        try
        {
            if (ModelState.IsValid)
            {
                //ss.StudentsTbls.AddObject(student); // Ignore this
                ss.SystemUsers.Add(users);
                ss.SaveChanges();
                return RedirectToAction("AdminIndex");
            }        
        }
        catch (Exception exception)
        {
        }

        return View(users);
    }   

现在,如果您将鼠标悬停在异常上或将其添加到Watch中,然后导航到异常详细信息,您将看到哪些特定列导致错误通常在表约束被消除时发生..

答案 1 :(得分:0)

如果您不了解内部如何运作,EntityValidationErrors很难处理。

您想要捕获的实际例外是DbEntityValidationException

此异常具有属性EntityValidationErrors,即IEnumerable<DbEntityValidationResult>

DbEntityValidationResult的属性ValidationErrorsIEnumerable<DbValidationError>

最后,DbValidationError有一个属性ErrorMessage,这是实际肉的位置。

将代码包装在try / catch块中并获取这些实际验证错误将如下所示:

try
{
    if (ModelState.IsValid)
    {
        ss.SystemUsers.Add(users);
        ss.SaveChanges();
        return RedirectToAction("AdminIndex");
    }
    return View(users);

}
catch (DbEntityValidationException ex)
{
    var errorMessages = ex.EntityValidationErrors
            .SelectMany(e => e.ValidationErrors)
            .Select(e => e.ErrorMessage)
            .ToList();
    // Here you can see the actual validation errors when you're debugging
}

当然,首先出现此异常的事实意味着控制器上的验证规则与数据库约束不匹配。

这是个人偏好的问题,但我通常不希望我的DAL捕获验证错误。如果您的BLL验证规则中存在任何错误,它应该只是您的最后手段。您应该这样对待它们:确保下次在您的DAL中发生这些问题时,您的控制器(或应用程序/业务层)中会发现这些问题。

相关问题