只有当属性的当前值为null时,才能设置EntityKey属性

时间:2011-12-15 17:28:15

标签: c# entity-framework-4

我正在尝试按以下方式执行EF更新,但继续收到此错误:

只有当属性的当前值为null时,才能设置EntityKey属性。

        using (hydraEntities db = new hydraEntities())
        {
            YouUser = db.youusers.Include("address").Include("entity").Include("youusercontacts.contact").Include("youuserlogins").Include("youusernotes.note").Include("youusernotes.youuser.entity").Where( yu => yu.YOUUserId.Equals(YOUUserId)).First();
        }

            YouUser.entity.FirstName = txtFirstName.Text;
            YouUser.entity.LastName = txtLastName.Text;
            YouUser.address.AddressLine1 = txtAddressLine1.Text;
            YouUser.address.AddressLine2 = txtAddressLine2.Text;
            YouUser.address.City = txtCity.Text;
            YouUser.address.State = ddlState.SelectedValue;
            YouUser.address.Zipcode = txtZipcode.Text;

            using (hydraEntities db = new hydraEntities())
            {
                db.youusers.AddObject(YouUser);
                db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
                db.SaveChanges();
            }

非常感谢有关如何解决此问题并执行上述声明的任何见解。

2 个答案:

答案 0 :(得分:11)

请勿在此方案中使用AddObject。它用于插入新实体,但您正在更新现有实体。请改用Attach

using (hydraEntities db = new hydraEntities())
{
    db.youusers.Attach(YouUser);
    db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
    db.SaveChanges();
}

答案 1 :(得分:0)

在我的场景中,我通过不同的线程一次多次添加对象。在执行此操作时,我必须锁定模型容器对象,以确保一次只处理一个对象。