2011-12-15 71 views
6

我試圖通過以下方式來執行的EF更新,但仍收到此錯誤:的的EntityKey屬性只能設置

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

將不勝感激,我如何能解決這個問題,並執行上面的語句中的任何見解。

回答

10

在這種情況下請勿使用AddObject。它用於插入新實體,但您正在更新現有實體。使用Attach代替:

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

我的方案,我將通過不同的線程同時對象幾次。這樣做時,我必須鎖定模型容器對象,以確保一次只處理一個對象。