实体框架错误:具有空EntityKey值的对象无法附加到对象上下文

时间:2011-12-13 22:11:51

标签: c# entity-framework entity-framework-4

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

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

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

任何想法出了什么问题,或者我怎样才能做得更好?

感谢。

2 个答案:

答案 0 :(得分:20)

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

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

P.S。您不必明确调用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

  

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

答案 1 :(得分:3)

来自MSDN

  

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

希望这会对你有所帮助。

相关问题