[英]Entity Framework - Marking entity as inactive when ref integrity stops record being deleted
I writing a simple method which should delete an entity from the database if possible, else it should mark the record as inactive if there is an integrity rule stopping the record from being deleted. 我编写了一个简单的方法,如果可能的话,该方法应该从数据库中删除实体,否则,如果存在完整性规则阻止将记录删除,则应将记录标记为非活动状态。
The code I have is: 我的代码是:
public ActionResult Delete(int id)
{
try
{
Service.Repository<TEntity>().Delete(id);
Service.SaveChanges(this.CurrentUser);
return this.RedirectToActionPermanent("Index");
}
catch (DbUpdateException)
{
Service.Repository<TEntity>().D
// Could not delete due to referential integrity so mark as inactive
var obj = Service.Repository<TEntity>().Find(id);
obj.Inactive = true;
// Error thrown here as obj is already marked as deleted
Service.SaveChanges(this.CurrentUser);
return this.RedirectToActionPermanent("Index");
}
}
The issue I have is that after when I run the code within the DbUpdateException and then execute save, another exception is thrown as the entity is still marked as 'deleted'. 我遇到的问题是,当我在DbUpdateException中运行代码然后执行保存后,由于该实体仍被标记为“已删除”,因此引发了另一个异常。 What is the best way of removing the original delete action from entity so I can try the save again? 从实体中删除原始删除操作的最佳方法是什么,以便我可以再次尝试保存?
Thanks 谢谢
You can refresh the entity from database then modify it again. 您可以从数据库刷新实体,然后再次对其进行修改。 You have to add a method to you repository in your case. 在这种情况下,您必须向存储库添加一个方法。
context.Refresh(RefreshMode.StoreWins, object);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.