Update non-scalar entities in Entity Framework v4
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 contac开发者_开发问答t 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();
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...
精彩评论