views:

41

answers:

1

Currently I am updating the scalar properties of the candidate object like so:

public Candidate EditCandidate(Candidate candidateToEdit)
    {
            _entities.Candidates.Attach(new Candidate { ID = candidateToEdit.ID });
            _entities.Candidates.ApplyCurrentValues(candidateToEdit);

            //update candidate.contact here somehow

            _entities.SaveChanges();

            return candidateToEdit;
    }

This only updates the Candidate scalars, since that's what ApplyCurrentValues does. I also need to update the candidate.contact object as well, currently it seems like the only option is to get the current candidate in the database via the candidateToEdit ID, grab the contact ID and updated it that way, but I'm not sure what the "best" way to do this is. candidateToEdit.contact has the values but not the ID since it doesn't get bound in my view. Do I change to the contact context and do that exactly the same way I updated the candidate?

Update: Solution

Based on Dan's answer below.

_entities.Candidates.Attach(candidateToEdit);
_entities.ObjectStateManager.ChangeObjectState(candidateToEdit, EntityState.Modified);
_entities.ObjectStateManager.ChangeObjectState(candidateToEdit.contact, EntityState.Modified);
_entities.SaveChanges();
+1  A: 

Since candidateToEdit has the contact information, I think you can do it like this. This assumes your _entities is the object context for EF.

public void Update(Candidate candidateToEdit)
{
   _entities.Candidates.Attach(candidateToEdit);
   _entities.ObjectStateManager.ChangeObjectState(candidateToEdit, EntityState.Modified);
   _entities.SaveChanges();
}

I think that saves all navigation properties...

Dan H
Thanks for your help, that did the trick, I added my code based on what you showed me here to my original post. The second line should be _entities.ObjectStateManager I think.
Graham
You are correct, the second line should be _entities.ObjectStateManager.ChangeObjectState(candidateToEdit, EntityState.Modified); Glad it worked for you!
Dan H