0

Why does this code not work? It inserts an object but does not delete it

public int Toggle(RequestArchive RequestArchiveObj)
{
   var ra = DataContext.RequestArchives.Where(rec => rec.UserId == RequestArchiveObj.UserId && rec.RequestId == RequestArchiveObj.RequestId);

   if(ra.Count() > 0)
   {
        foreach (var item in ra)
        {                    
            DataContext.DeleteObject(item);
        }
   }
   else
   {
        DataContext.AddToRequestArchives(RequestArchiveObj);
   }

   DataContext.SaveChanges();
   return RequestArchiveObj.Id;
}
f_puras
  • 2,521
  • 4
  • 33
  • 38
Ali Foroughi
  • 4,540
  • 7
  • 42
  • 66

1 Answers1

1

There's a potentially dangerous issue with your code and your problem might relate to that:

If you loop through your query object (the object returned by DataContext.RequestArchives.Where()) without executing it, you're going to have a roundtrip to the database for every single item in the loop. This is called the N+1 selects problem.

You can mitigate this using the ToList() method:

var ra = DataContext.RequestArchives
                    .Where(rec => 
                           rec.UserId == RequestArchiveObj.UserId && 
                           rec.RequestId == RequestArchiveObj.RequestId)
                    .ToList(); // this executes the query
// ...
foreach (var item in ra) // without ToList() this will query every item by itself
{                    
    DataContext.DeleteObject(item); // and this might collide with the query
}

I'm not sure about this, but maybe the deletion problem occurs because you try to delete objects while still querying them through the foreach loop. If that is the case, it should work once you're using ToList() as recommended above.

Community
  • 1
  • 1
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108