目前我正在更新候选对象的标量属性,如下所示:
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;
}
这只会更新候选标量,因为ApplyCurrentValues就是这样做的。我还需要更新candidate.contact对象,目前唯一的选择似乎是通过candidateToEdit ID获取数据库中的当前候选人,获取联系人ID并以这种方式更新,但我不确定这样做的“最佳”方法是什么。candidateToEdit.contact具有值,但没有ID,因为它在我的视图中没有绑定。我是否更改为联系人上下文,并以更新候选人的方式进行更改?
更新:解决方案
基于
Dan's answer
下面。
_entities.Candidates.Attach(candidateToEdit);
_entities.ObjectStateManager.ChangeObjectState(candidateToEdit, EntityState.Modified);
_entities.ObjectStateManager.ChangeObjectState(candidateToEdit.contact, EntityState.Modified);
_entities.SaveChanges();