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

.net asp.net asp.net-mvc c# entity-framework-6

Question

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.

1
1
4/18/2020 5:31:01 AM

Accepted Answer

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
}

2
4/18/2020 3:47:36 AM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow