I'm writing test code that needs to clean up the entities it creates when done. To account for the possibility that the test ended prematurely, I run the cleanup code when the test is initialized as well.
I'm using this recommendation
https://stackoverflow.com/a/5522422/141172
var category = new Category() { CategoryId = 1 };
context.Categories.Attach(category);
context.Categories.Remove(category);
context.SaveChanges();
to delete the entities. However, if the entities were already deleted (e.g. previous test run successfully cleaned up),
ctx.SaveChanges();
throws an Exception:
Store update, insert, or delete statement affected an unexpected number of rows (0)
That makes perfect sense, but just catching the Exception is a bit awkward. Is there a cleaner way to accomplish this without introducing an extra trip to the DB to check for the entity?