Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework Error: An object with a null EntityKey value cannot be attached to an object context

In my application I have the following code...

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

This code calls a method on a dataManager object that utilizes Entity Framework...

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

    }

The insert on this code works just fine. But when I try to perform an update I'm getting an error saying: "An object with a null EntityKey value cannot be attached to an object context."

It occurs on this line of code: entities.Attach(userInfo);

What I'm trying to accomplish is to avoid making a round trip to the database just to select the record that I will later make changes to and update, thus making two round trips to the database.

Any ideas what is going wrong, or how I could better accomplish this?

Thanks.

like image 595
jdavis Avatar asked Dec 13 '11 22:12

jdavis


2 Answers

Seems like you're using EF 4.1+
You have to tell EF that you want your entity to be updated (Modified state):

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

P.S. You don't have to explicitly call Attach. It's done under the hood.

Update:
based on your comments, you're using EF 4.0. Here's what you have to do to attach your object as modified in EF 4.0:

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

You cannot use Attach method. From http://msdn.microsoft.com/en-us/library/bb896271.aspx:

If more than one entity of a particular type has the same key value, the Entity Framework will throw an exception. To avoid getting the exception, use the AddObject method to attach the detached objects and then change the state appropriately.

like image 67
Kamyar Avatar answered Nov 12 '22 13:11

Kamyar


From MSDN

The object that is passed to the Attach method must have a valid EntityKey value. If the object does not have a valid EntityKey value, use the AttachTo method to specify the name of the entity set.

Hope this will help you.

like image 22
Alex Kovanev Avatar answered Nov 12 '22 14:11

Alex Kovanev