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

I am trying to perform an EF update as follows, but keep getting 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(); } 

I would really appreciate how I can fix this and fulfill the above expression.

+6
source share
2 answers

Do not use AddObject in this scenario. It is intended to insert a new object, but you are updating an existing one. Use Attach instead:

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

In my script, I added objects several times at once through different threads. I had to lock the Model Container object while doing this to make sure that only one object would be processed at a time.

0
source

Source: https://habr.com/ru/post/903863/


All Articles