尝试提交时,一个或多个实体的验证失败

时间:2015-07-28 14:02:08

标签: c# asp.net-mvc controller viewmodel

我在我正在创建的帮助台软件中遇到问题。当用户尝试编辑知识库并将其保存在我的存储库库中的提交方法时,他们会收到此错误:

enter image description here

这是模型控制器代码,我将模型字段与视图模型字段匹配,然后我提交更改:

 [HttpPost]
        public ActionResult EditTechKnowledgebase(EditKnowledgebase editknowledgebase)
        {

            if (ModelState.IsValid)
            {
                Knowledgebase knowledgebase = new Knowledgebase();
                knowledgebase.Category = editknowledgebase.Category;
                knowledgebase.CategoryId = editknowledgebase.CategoryId;
                knowledgebase.CreatedBy = editknowledgebase.CreatedBy;
                knowledgebase.CreatedById = editknowledgebase.CreatedById;
                //knowledgebase.CreatedDate = editknowledgebase.CreatedDate;
                knowledgebase.Description = editknowledgebase.Description;
                knowledgebase.Note = knowledgebase.Note;

                knowledgebases.Update(knowledgebase);
                knowledgebases.Commit();

                return RedirectToAction("TechKnowledgebaseList", new { createdById = editknowledgebase.CreatedById, categoryId = editknowledgebase.CategoryId, typeId = editknowledgebase.TypeId });
            }
            else
            {
                ViewBag.CategoryId = new SelectList(db.Categories.Where(c => c.Status == 1), "CategoryId", "CategoryName");
                ViewBag.TypeId = new SelectList(db.Roles, "RoleId", "RoleDescription");

                return View(editknowledgebase);
            }

        }

1 个答案:

答案 0 :(得分:0)

问题是由您保存的内容与数据库架构不匹配引起的。例如,它可能试图在非空字段中保存null,或者将一个double保存到int字段,或者将一个小于1900-01-01的日期保存在datetime字段中。

您可以像这样捕获DBValidationExceptions:

try
{
    knowledgebases.Update(knowledgebase);
    knowledgebases.Commit();
}
catch (DbEntityValidationException ex)
{
    foreach (var validationErrors in ex.EntityValidationErrors)
    {
        foreach (var validationError in validationErrors.ValidationErrors)
        {
            Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
        }
    }
}

这将写出导致错误的每个属性。

通过使用Required属性装饰viewmodel属性,使非空字段成为必需字段,然后这将使ModelState.IsValid测试失败并进行处理。对于用户无权访问的非空字段,请确保它们具有默认值。