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

jda*_*vis 9 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
        });
    }
Run Code Online (Sandbox Code Playgroud)

此代码调用使用实体框架的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;
        }

    }
Run Code Online (Sandbox Code Playgroud)

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

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

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

任何想法出了什么问题,或者我怎么能更好地完成这个?

谢谢.

Kam*_*yar 20

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

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

PS你不必明确打电话Attach.它是在引擎盖下完成的.

更新:
根据您的评论,您使用的是EF 4.0.以下是在EF 4.0中修改对象时需要做的事情:

 ctx.AddObject("userInfoes", userInfo);
 ctx.ObjectStateManager.ChangeObjectState(userInfo, EntityState.Modified);
 ctx.SaveChanges();  
Run Code Online (Sandbox Code Playgroud)

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

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