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 asp.net-mvc c# entity-framework linq-to-sql

Question

I get an error message when trying to delete a user and associated objects. The error message is The object cannot be deleted because it was not found in the ObjectStateManager.

CONTROLLER

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

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

        _repository.DeleteUser(user);

        return RedirectToAction("Index");
    }

REPOSITORY

public void DeleteUser(User user)
            {            
                foreach (Follower follower in user.Followers)
                    _db.Followers.DeleteObject(follower);

                foreach (Comment comment in user.Comments.ToList())
                    _db.Comments.DeleteObject(comment);   

                _db.Users.DeleteObject(user);
            }

Am I missing something?

1
3
3/23/2011 2:22:58 AM

Accepted Answer

What's your code for the _userRepository.GetByUserName(UserName) look like?

What it sounds like to me is that you're getting a user from one context, and attempting to delete from another.

E.g.

User myUser = null;

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

using(MyData data = new MyData())
{
    data.DeleteUser(myUser);
}

The 2nd "data" doesn't know about that user, because it didn't retrieve it.

Instead, you'd have to something like

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

Syntax might not be exactly right, but essentially you need to set that your user object is an entity in that data context, and that it's state is Deleted.

You'd have to do something similar i you wanted to modify an existing object (set state to EntityState.Modified)

5
3/23/2011 2:52:10 AM


Related Questions





Related

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