简体   繁体   中英

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'. What is the best way of removing the original delete action from entity so I can try the save again?

  • Edit I meant to say that I have seen lots of people stating that I should dispose of the existing context and get a new one. To me this seems a little wrong in this context as I am injecting the context upon each Http request via Unity.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM