Multiple problems when deleting from a database

时间:2015-07-28 17:15:29

标签: sql asp.net-mvc

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?

1 个答案:

答案 0 :(得分:0)

我的问题是因为我实际上已经删除了两次实体。对于将来遇到类似错误的任何人,请务必仔细检查您的代码是否有重复的陈述。