Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The EntityKey property can only be set when the current value of the property is null

i'm trying to execute an EF update in the following manner but continue to receive this error:

The EntityKey property can only be set when the current value of the property is null.

        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();
            }

Would greatly appreciate any insight on how I can fix this and execute the statement above.

like image 236
99823 Avatar asked Dec 15 '11 17:12

99823


1 Answers

Don't use AddObject in this scenario. It is for inserting a new entity but you are updating existing one. Use Attach instead:

using (hydraEntities db = new hydraEntities())
{
    db.youusers.Attach(YouUser);
    db.ObjectStateManager.ChangeObjectState(YouUser, System.Data.EntityState.Modified);
    db.SaveChanges();
}
like image 64
Ladislav Mrnka Avatar answered Oct 31 '22 08:10

Ladislav Mrnka