I am facing a problem with Entity Framework Core in an .NET Core REST API.
Example Data Model:
Table House (id, name) Table Rooms (id, houseId, name)
A house can have multiple rooms and a room can only be in one house.
My problem occurs when I delete a room. Every time the user makes a request to delete a room I check if the room was the last in the house and if it was the last I delete the (empty) house too.
Room room = dbContext.Room
.Include(r => r.House).ThenInclude(h => h.Rooms)
.Where(r => r.id == id)
.SingleOrDefaultAsync();
if (room.House.Rooms.Count > 1) {
// other rooms are present
dbContext.Room.Remove(room);
} else {
// delete house if it is the last room
dbContext.House.Remove(room.House);
}
dbContext.SaveChanges();
The problem is that our UI does not delete a house in one call, it calls delete room for each room in the house (and expects that the house is deleted automatically with the last room). This causes the problem. The calls come short after each other that every room loads the house entity, checks if it is the last room, recognizes other rooms, the room gets deleted, the empty house remains.
Is this anyhow possible to solve (so the empty house does not remain) e.g. with transactions?
DbContext
lifetime issue.