I'm having a problem which happens when i try to delete a few registers from the database.
The problem is when one of those people that I'm trying to delete have an bill registered or another thing that I can't delete. Occurs error on 'SaveChenges()' because people have reference on another table, and will catch my exception and supposedly try to delete the next 'people', BUT in this next people occurs the same error, and in the 'Exception.InnerException' that shows me, there is the same Id of my previous 'people', and in this way my register are never deleted, unless no one of those peoples that I'm trying to delete occurs an error, or I'm trying to delete one by one for another route ("which uses the same 'DeletePeople(People people)'")
public IActionResult DeletePeople(long[] ids){
var peoples = _peopleRepository.GetPeoples(ids);
var nonDeleted = 0;
foreach (var people in peoples){
var deleted = DeletePeople(people);
if(!deleted)
nonDeleted++;
}
return Json(new { nonDeleted, total = peoples.Count() });
}
public bool DeletePeople(People people){
var transaction = _peopleRepository.BeginTransaction();
try{
_contactsPeopleRepository.RemoveRange(people.Contacts);
_contactRepository.RemoveRange(people.Contacts.Select(x => x.Contact))
if(people.Client != null)
_clientRepository.Remove(people.Client);
//
Remove a few other things witch have reference with 'people' at the same way
//
_peopleRepository.Remove(people)
_peopleRepository.SaveChanges();
transaction.Commit();
return true;
}
catch{
transaction.Rollback();
return false;
}
}
Below is my 'GetPeoples' on the repository.
public IEnumerable<People> GetPeoples(long[] ids){
return GetAll()
.Include(x => x.Client)
//Here there are a few more includes that I try to remove
.Where(x => ids.Contains(x.Id))
}
(My English is not very good, but I tried my best to describe my problem)
I tried to use asynchronous methods, and get the peoples from my database one by one inside my method 'DeletePeople(People people)', which in this case use to receive just and 'id', but nothing seems to work. And also, I tried to research if someone else already have this problem and found nothing :(