0

I am attempting to remove an object from my sql database. I have been using this same method in multiple places and they all work fine except for here.

My Code:

foreach (TestCase testCase in testCaseList)
        {
            db.TestCases.Remove(testCase);
            await db.SaveChangesAsync();
        }

The error that I get from this code is: "The object cannot be deleted because it was not found in the ObjectStateManager"

I found a solution to this problem which was adding an attach. The resulting code was:

foreach (TestCase testCase in testCaseList) 
    {
        db.TestCases.Attach(testCase);
        db.TestCases.Remove(testCase);
        await db.SaveChangesAsync();
    {

With this code, I get the following error: "Store update, insert, or delete statement affected an unexpected number of rows(0)." I found some information on this error, but nothing that seemed to apply to my issue. Is there a specific reason these issues are arising and what can I do to solve the errors?

tereško
  • 58,060
  • 25
  • 98
  • 150
Jon
  • 278
  • 8
  • 23
  • possible duplicate of [Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."](http://stackoverflow.com/questions/1836173/entity-framework-store-update-insert-or-delete-statement-affected-an-unexpec) – HaveNoDisplayName Jul 28 '15 at 17:25
  • Are you aware of how this could be caused? – Jon Jul 28 '15 at 17:31
  • Never-mind, I was accidentally removing it twice. Thanks anyway. – Jon Jul 28 '15 at 17:32

1 Answers1

0

My issue resulted from the fact that I was actually removing the entity twice. For anybody that gets similar errors in the future, be sure to double check your code for duplicate statements.

Jon
  • 278
  • 8
  • 23
  • Please use the edit link on your question to add additional information. The Post Answer button should be used only for complete answers to the question. – Sruit A.Suk Jul 29 '15 at 01:06
  • @SruitA.Suk I saw this as a complete answer. My issue resulted from not seeing that I duplicated code and the answer for people seeing similar issues is to double check your code. – Jon Jul 29 '15 at 15:20