Home > Mobile >  problem removing an object from database entityframework asp.net
problem removing an object from database entityframework asp.net

Time:01-15

i have 3 classes that are connected to eachother
class shake
class VmShake , that has 2 vars 1 is a shake object and the other is int amount
class Cart that has a list of VMShake

i first delete it from the cart , afterwards delete it from the vmshake and finally delete the shake itself.

when i delete it from the site , sql deletes it from shakes table . but in the VMshake table the row still appears with null values .

what can cause this problem and how to overcome it

here's a snippet:

 ShakesAndTusafim shake = DataLayer.Data.shakesAndTusafims.ToList().Find(x => x.ID == id);
           
    if (shake != null)
            {
                int tempId = shake.ID;
               

                foreach (Cart cart in DataLayer.Data.Carts)
                {
                    foreach (VMShakes vm in cart.shakes)
                    {
                        if (vm.shakes.ID == tempId)
                        {
                            cart.shakes.Remove(vm);
                            break;
                        }
                    }

                }
                foreach (VMShakes Shake in DataLayer.Data.VMShakes)
                { 
                if(Shake.Id== tempId)
                        DataLayer.Data.VMShakes.Remove(Shake);
                }


                DataLayer.Data.shakesAndTusafims.Remove(shake);

            }
            DataLayer.Data.SaveChanges();

CodePudding user response:

First you delete it from the cart and that done well , The issue happens when you are deleting it from the VmShake , if you look at your code :

  foreach (VMShakes Shake in DataLayer.Data.VMShakes)
  { 
               if(Shake.Id== tempId)
                    DataLayer.Data.VMShakes.Remove(Shake);
  }

you are not looking for a shake having tempId to delete , instead you are trying to delete a vmShake that has Id equal to tempId. It will work if you change it to this :

  foreach (VMShakes vmShake in DataLayer.Data.VMShakes)
  { 
            if(vmShake.shake.Id== tempId)
                    DataLayer.Data.VMShakes.Remove(vmShake);
  }
  • Related