-1

Here is my Code,

  db.Set<T>().Remove(item);
                db.SaveChanges();

And i got this error.

{"The object cannot be deleted because it was not found in the ObjectStateManager."}

i tried many ways to fix that problem, but i couldn't. How can id fix ?

thank you all.

Dursun ICCAN
  • 69
  • 1
  • 9
  • 1
    Please try to show what exactly you tried and why that didn't help. See for example [The object cannot be deleted because it was not found in the ObjectStateManager](http://stackoverflow.com/questions/7791149/the-object-cannot-be-deleted-because-it-was-not-found-in-the-objectstatemanager). If you think none of the questions you found apply to your situation, you should show where `item` comes from. – CodeCaster Mar 22 '14 at 14:13
  • thank you for your help but i already tried ways on that link – Dursun ICCAN Mar 22 '14 at 14:46
  • Then explain what happened when you tried that. What is told on that link should work. – CodeCaster Mar 22 '14 at 14:47

1 Answers1

0

Most likely you are trying to remove an object that doesn't come from your DbContext. For example if your object comes from a web form in ASP .Net MVC it has noting to do with the database until you attach it to the database.

There are 2 things you can do to be able to remove your item:

db.Set<T>.Attach(item);
// now you should be able to remove it

or

item = db.Set<T>.Single(x => x.Id == itme.Id);
// now you should be able to remove it

EDIT

You should also make sure that you're not trying to attach an object that already is attached. Take a look at the EntitState:

db.Entry(item).State

Andrzej Gis
  • 13,706
  • 14
  • 86
  • 130
  • thank you for your help but; when is use db.Set().Attach(item) i got this error {"An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key."} – Dursun ICCAN Mar 22 '14 at 14:44
  • item = db.Set.Single(x => x.Id == itme.Id); i can't use like this beacuse visual studio does not know entity TYPE – Dursun ICCAN Mar 22 '14 at 14:45
  • i really don't understand when i track entity db.Entry(item).State is Detached and when i use db.Set().Attach(item) i got exception like this {"An entity object cannot be referenced by multiple instances of IEntityChangeTracker."} – Dursun ICCAN Mar 22 '14 at 15:06
  • 1
    @DursunICCAN Maybe you have multiple instances of you DbContext at the same time and there are conflict between them? – Andrzej Gis Mar 22 '14 at 15:08