In MVC/Entity Framework, here's how to remove objects: Because it was not detected in the ObjectStateManager, the object could not be destroyed.

.net c# entity-framework linq-to-sql


When attempting to remove a user and any related items, I get an error notice. Zzz-5-Zzz is the error message.


[Authorize, HttpPost]
    public ActionResult DeleteUser(string UserName)
        User user = _userRepository.GetByUserName(UserName);

        if (user == null)
            return new FileNotFoundResult();


        return RedirectToAction("Index");


public void DeleteUser(User user)
                foreach (Follower follower in user.Followers)

                foreach (Comment comment in user.Comments.ToList())


Do I have anything missing?

3/23/2011 2:22:58 AM

Accepted Answer

The code you use for the_userRepository.GetByUserName(UserName) seem like?

I get the impression that you are trying to remove from one context while obtaining a user from another.


User myUser = null;

using(MyData data = new MyData())
    myUser = data.GetUserById(1);

using(MyData data = new MyData())

Due to the fact that it was not retrieved, the second "data" is unaware of that user.

Instead, you would need to do something similar.

using(MyData data = new MyData())
    data.Context.Entry(myUser).State = EntityState.Deleted;

You need to set that your user object is an entity in that data context and that its state is Deleted, even if the syntax may not be perfect.

If you wanted to change an existing item, you would have to follow a similar procedure (set state to EntityState.Modified)

3/23/2011 2:52:10 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow