简体   繁体   中英

How to check if a delete operation succeeds in ASP.NET MVC using Entity Framework

Is there a way to determine if an entity record gets deleted successfully? Please see code and comments below.

var myProductID = 123;

var productToDelete = await db.Products.Where(p => p.ID == myProductID).FirstOrDefaultAsync();

if (productToDelete != null)
{
    db.Entry(productToDelete).State = EntityState.Deleted;
    await db.SaveChangesAsync();
}

// At this point, is there a way to check whether the delete operation went thru successfully? In other words, I want to check if the record really got deleted from the database. I could run a re-query, but I don't want to do that.

I am using .NET 4.7.2, ASP.NET MVC 5 and Entity Framework 6.

If the operation fails then you're going to get some kind of DbUpdateException when you call SaveChangesAsync. Because you are awaiting there, when the operation is complete it has been deleted. If for some reason you dont trust it then try querying for that entity again. I wouldnt suggest that though.

You can see the docs here that show you'll get an exception if the db operation fails

https://docs.microsoft.com/en-us/dotnet/api/system.data.entity.dbcontext.savechanges?view=entity-framework-6.2.0

db.SaveChanges returns an int whereas they're the number of records affected hence you could check by db.SaveChanges() >= 0 ;

if (productToDelete != null)
{
   db.Entry(productToDelete).State = EntityState.Deleted;
   int changes = await db.SaveChangesAsync();

   if(changes>=0){
      // ... success
   }
   // it will throw an exception if failed
}

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