更新Entity Framework v4中的非标量实体 [英] Update non-scalar entities in Entity Framework v4

查看:80
本文介绍了更新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;
    }

这只会更新Candidate标量,因为这是ApplyCurrentValues所做的。我还需要更新候选人.contact对象,目前看来,唯一的选择是通过候选人编辑ID获取当前候选人在数据库中,抓住联系人ID并以这种方式更新,但我不确定什么是最好的方式来做到这一点。 candidateToEdit.contact具有值而不是ID,因为它在我的视图中没有被绑定。我更改为联系人上下文,并且做出与我更新候选人完全相同的方式?

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?

更新:解决方案

根据 Dan的回答

_entities.Candidates.Attach(candidateToEdit);
_entities.ObjectStateManager.ChangeObjectState(candidateToEdit, EntityState.Modified);
_entities.ObjectStateManager.ChangeObjectState(candidateToEdit.contact, EntityState.Modified);
_entities.SaveChanges();


推荐答案

由于candidateToEdit有联系信息,我想你可以像这样做。这假设你的_entities是EF的对象上下文。

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

这篇关于更新Entity Framework v4中的非标量实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆