如何在重新提交之前清除以前的DBContext DbEntityValidationException错误

问题描述 投票:0回答:1

我有一个简单的表单来向数据库添加一个名为“ActionItem”的对象。简化的代码如下:

[HttpPost]
public ActionResult ActionItem(ActionItem model)
{
   try
   {
       string error = string.Empty;
       actionItemRepository.DBContext.ActionItems.Add(model);
       actionItemRepository.DBContext.SaveChanges();
   }
   catch (DbEntityValidationException dbEx)
   {
       DbValidationError dbError = dbEx.EntityValidationErrors.First().ValidationErrors.First();
       error = dbError.PropertyName + ": " + dbError.ErrorMessage;
       return null;
   }
   catch(Exception ex) {....}
   return View(some updated obj);
 }


public partial class ActionItem
{
    public long AIID { get; set; }
    public System.DateTime DueDay { get; set; }
    public Nullable<long> EntityID { get; set; }
    public int EntityType { get; set; }
    public int TotalProgress { get; set; }
    public int CurrentProgress { get; set; }
    public int Status { get; set; }
    public string Name { get; set; }
    public string Note { get; set; }
    public Nullable<long> SeriesID { get; set; }
    public Nullable<int> SeriesCount { get; set; }
    public Nullable<int> Priority { get; set; }

    public virtual ActionSeries ActionSeries { get; set; }
}

由于我忘了检查actionItem对象的名称是否需要不超过50个字符,因此SaveChanges()会抛出一个DbEntityValidationException,这很酷。但是当我在UI上修复它并提交正确的名称时,我可以在SaveChanges()之前跟踪并确认名称更短,但是再次抛出相同的异常。它似乎总是记住以前的错误,不想重置。有没有办法清除以前的DBContext错误?

谢谢!

asp.net-mvc entity-framework dbcontext
1个回答
0
投票

使用ModelState.Clear();这将清除以前的错误

© www.soinside.com 2019 - 2024. All rights reserved.