Reputation: 103
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.
Upvotes: 2
Views: 2724
Reputation: 6130
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
}
Upvotes: 4
Reputation: 4151
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
Upvotes: 2