当Dbcontext的任何实体中发生任何实体验证错误时,它在当前上下文中将持续存在。如果我们下次为任何操作(添加,更新或删除)传递有效数据,则先前的验证错误仍然存在,此后将不处理任何操作。我认为这是一个错误。如果传递了新数据,则应将其删除。如何从当前上下文中删除该验证错误?
答案 0 :(得分:0)
当我们将实体添加到集合时,将其添加到其本地存储中,并且由于该实体的本地存储不清晰并且在那里仍然有旧条目,我们一直收到错误消息。因此,您必须从当前上下文中删除那些验证错误。您可以查看以下链接以了解更多详细信息:http://www.binaryintellect.net/articles/c1bff938-1789-4501-8161-3f38bc465a8b.aspx
if(ex is DbEntityValidationException dbException)
{
foreach (var eve in dbException.EntityValidationErrors)
{
foreach (var ve in dbException.EntityValidationErrors.SelectMany(entity => entity.ValidationErrors))
{
sbErrorList.AppendLine(
String.Format(" Entity: \"{0}\", Action: \"{1}\", Property: \"{2}\", Value: \"{3}\", Error: \"{4}\"",
eve.Entry.Entity.GetType().Name,
eve.Entry.State,
ve.PropertyName,
eve.Entry.CurrentValues.GetValue<object>(ve.PropertyName),
ve.ErrorMessage)
);
}
#region Removing Entity Validation Error from current context : Rollback Changes
// checks the State property of the DbEntityEntry causing the error
switch (eve.Entry.State)
{
case EntityState.Added:
eve.Entry.State = EntityState.Detached; // changed to Detached so that the entry won't be considered a part of the DbSet for future calls
break;
case EntityState.Modified:
eve.Entry.CurrentValues.SetValues(eve.Entry.OriginalValues); // the modified values (the values causing the error) are flushed out by replacing them with the OriginalValues.
eve.Entry.State = EntityState.Unchanged;
break;
case EntityState.Deleted:
eve.Entry.State = EntityState.Unchanged; // changed to Unchanged so that the entity is undeleted
break;
}
#endregion
}
}