My problem is pretty straightforward, I Have a page where Admins can Manage the list of authorized admin but my problem is that there should always be at least 1 Admin left in the database so I Wrote This simple if that checks the number of Admins in the database should be higher than 1 before deleting
Here is my controller delete action
public ActionResult DeleteAdmin(int idAdmin) { using (InscriptionFormationEntities dbm = new InscriptionFormationEntities()) { Administrateurs admin = dbm.Administrateurs.FirstOrDefault(x => x.id == idAdmin); if(admin.NomLogin == Session["utilisateur"].ToString()) { ModelState.AddModelError("Current User", "You can't delete Yourself"); } if(dbm.Administrateurs.ToList().Count <= 1) { ModelState.AddModelError("LastAdmin", "At least 1 admin must be left"); } if (ModelState.IsValid) { dbm.Administrateurs.Remove(admin); dbm.SaveChanges(); } List<Administrateurs> ListeAdmin = dbm.Administrateurs.ToList(); return RedirectToAction("Utilisateurs", "Admin"); } } This code Works perfectly fine expect in one case : if there are 2 Admin left and they try to delete eachother at the same time they will be able to. I Tried to change where I put the condition(for instance just before the delete) but still the condition always returns false. So I was wondering if there was a way to prevent this like defining that only 1 instance can delete at a time or something like that.
EDIT
I looked into this question: How can I lock a table on read, using Entity Framework?
but it dosen't solve my problem because i don't want to lock on the read but on the delete instead, because if I lock the read only 1 person will be able to access that page at a time ( it could work in a worse case scenario but I hope there is a better solution)