1

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?

Community
  • 1
  • 1
Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • 1
    When I test like this, I usually just wrap everything in a TransactionScope and at the end of the test, I don't commit the transaction. Is this something you could do? – Davin Tryon Mar 21 '12 at 23:24

1 Answers1

2

The easiest and cleanest way to do this is not to use a fake entity, but to run a simple SQL query:

var rows = context.Database.ExecuteSqlCommand("delete Category where ...");
if (rows == 0)
    //nothing was deleted
Diego Mijelshon
  • 52,548
  • 16
  • 116
  • 154