entity framework错误:具有null EntityKey值的对象无法附加到对象上下文

在我的应用程序中,我有以下代码……

public Boolean SaveUserInformation(UserInfoDTO UserInformation) { return dataManager.SaveUserInfo(new UserInfo() { UserInfoID = UserInformation.UserInfoID.HasValue ? UserInformation.UserInfoID.Value : 0, UserID = UserInformation.UserID, ProxyUsername = UserInformation.ProxyUsername, Email = UserInformation.Email, Status = UserInformation.Status }); } 

此代码调用使用Entity Framework的dataManager对象上的方法…

  public Boolean SaveUserInfo(UserInfo userInfo) { try { //Validate data prior to database update if (userInfo.UserID == null) { throw new Exception("UserInfoDomainModel object passed to PriorityOne.Data.DataManager.SaveUserInfo with UserID property set to NULL."); } if (userInfo.ProxyUsername == null) { throw new Exception("UserInfoDomainModel object passed to PriorityOne.Data.DataManager.SaveUserInfo with ProxyUsername property set to NULL."); } if (userInfo.Email == null) { throw new Exception("UserInfoDomainModel object passed to PriorityOne.Data.DataManager.SaveUserInfo with Email property set to NULL."); } if (userInfo.UserInfoID == 0) { //Perform Insert using (PriorityOneEntities entities = new PriorityOneEntities()) { entities.UserInfoes.AddObject(userInfo); entities.SaveChanges(); } } else { //Perform Update using (PriorityOneEntities entities = new PriorityOneEntities()) { entities.Attach(userInfo); entities.SaveChanges(); } } return true; } catch (Exception ex) { //TODO: Log Error return false; } } 

此代码上的插入工作正常。 但是当我尝试执行更新时,我收到一条错误消息:“具有空EntityKey值的对象无法附加到对象上下文。”

它出现在这行代码中:entities.Attach(userInfo);

我想要完成的是避免到数据库的往返只是为了选择我稍后将更改和更新的记录,从而进行两次往返数据库。

什么是错误的想法,或者我怎样才能更好地完成这个?

谢谢。

好像你正在使用EF 4.1+
您必须告诉EF您希望更新您的实体(修改状态):

 //Perform Update using (PriorityOneEntities entities = new PriorityOneEntities()) { entities.Entry(userInfo).State = EntityState.Modified; entities.SaveChanges(); } 

PS您不必显式调用Attach 。 它是在引擎盖下完成的。

更新
根据您的评论,您使用的是EF 4.0。 以下是在EF 4.0中修改附加对象所需执行的操作:

  ctx.AddObject("userInfoes", userInfo); ctx.ObjectStateManager.ChangeObjectState(userInfo, EntityState.Modified); ctx.SaveChanges(); 

您不能使用Attach方法。 来自http://msdn.microsoft.com/en-us/library/bb896271.aspx :

如果特定类型的多个实体具有相同的键值,则entity framework将抛出​​exception。 为避免出现exception,请使用AddObject方法附加分离的对象,然后相应地更改状态。

来自MSDN

传递给Attach方法的对象必须具有有效的EntityKey值。 如果对象没有有效的EntityKey值,请使用AttachTo方法指定实体集的名称。

希望这会帮助你。