-1

I have two entities Customers & PhoneNumbers, my customer entity has collection of phone numbers, when I add new customer and add some phone numbers, then press click remove customer button, EF throw 'Adding a relationship with an entity which is in the Deleted state is not allowed'. this question already asked but I could not find any solution to solve this problem. I use below code to remove a customer in CustomerRepository:

public override void Remove(Customer model)
{
    Context.Customers.Remove(model);
}
mohsen mousavi
  • 262
  • 2
  • 7
  • 2
    You're holding onto the context, which causes problems like this. When you want to do something in the database, simply create a context, use it, then dispose of it. The context is holding a new relationship between the customer and some other model, and it's trying to save that relationship at the same time it's trying to delete the model. Create, update, save, dispose. –  May 11 '18 at 16:32

1 Answers1

1

Don't Operate on same DbContext. First dispose this object and create new dbContext and try to operate on new one. Otherwise your changetracker will be ambiguous with your operation intent and you will get this error. Here is one more solution : Removing Objects With a Relationship from DbContext

Rajput
  • 2,597
  • 16
  • 29