'Database operation expected to affect 1 row(s) but actually affected 0 row(s) entity framework core

I have the following code

 try
    {
        using (var context = await PrepareDatabase())
        {
            // Update temp roles by removing one row, this should affect that RemoveOldRoles below is removing rows from the Role-table
            var entity = context.TempRawRoles.Where(x => x.Account == "brkar4").FirstOrDefault();
            context.TempRawRoles.Remove(entity);
            await context.SaveChangesAsync();

            await CleanUp(context);
        }
    }
    catch(Exception ex)
    {
        throw;
    }

Here is my CleanUp

   private async Task CleanUp(SecurityContext context)
        {
            try
            {
                // Get only the global ids that belongs to our test accounts
                List<Guid> ids = await GetCreatedTestGlobalIds(context);

                List<IdentityEntity> identities = await context.Identities.Where(x => ids.Contains(x.GlobalId)).ToListAsync();

                context.Identities.RemoveRange(identities);

                await context.SaveChangesAsync(); // Throws error

            }
            catch(Exception ex)
            {
                throw;
            }
        }

When await context.SaveChangesAsync(); is executed in my CleanUp, I get the following error:

Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.

I guess it has something todo with this: context.TempRawRoles.Remove(entity);

But how can I fix this?



Solution 1:[1]

    private async Task CleanUp(SecurityContext context)
    {
        try
        {
            // Get only the global ids that belongs to our test accounts
            List<Guid> ids = await GetCreatedTestGlobalIds(context);

            List<IdentityEntity> identities = await context.Identities.Where(x => ids.Contains(x.GlobalId)).ToListAsync();

            await context.Identities.RemoveRangeAsync(identities); // modify here

            await context.SaveChangesAsync(); 

        }
        catch(Exception ex)
        {
            throw;
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 paulsm4