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

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

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);
            }

Do I have anything missing?

1
3
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.

E.g.

User myUser = null;

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

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

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;
    data.SaveChanges();
}

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)

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