views:

266

answers:

4

Hi

I have an ASP.NET Page that updates registered User Address Details for a selected record. Below is the Update method that i am calling from Controller.

When i am calling ApplyPropertyChanges method, I am getting the below error. Did anyone run into the same error while updating the record with Entity Framework.

Appreciate your responses.

Error Message:

The existing object in the ObjectContext is in the Added state. Changes can only be applied when the existing object is in an unchanged or modified state.

My Update Method Code:

[HttpPost]
    public bool UpdateAddressDetail([Bind(Prefix = "RegUser")] AddressDetail regUserAddress, 
                        FormCollection formData)
    {
    regUserAddress.AD_Id = 3;
        regUserAddress.LastUpdated = HttpContext.User.Identity.Name;
        regUserAddress.UpdatedOn = DateTime.Now;
        regUserAddress.AddressType = ((AddressDetail)Session["CurrentAddress"]).AddressType ?? "Primary";
        regUserAddress.Phone = ((AddressDetail)Session["CurrentAddress"]).Phone;
        regUserAddress.Country = ((AddressDetail)Session["CurrentAddress"]).AddressType ?? "USA";

        miEntity.ApplyPropertyChanges(regUserAddress.EntityKey.EntitySetName, regUserAddress);
        miEntity.SaveChanges();
        return true;
    }
+1  A: 

Hey,

The error is the object is detached from the context, and ApplyPropertyChanges thinks the object is added because it isn't attached. So you would need to query from the data context or get an attached form and then apply the changes then.

HTH.

Brian
A: 

ApplyPropertyChanges() is only necessary when copying changes from a detached object to an attached object.

Change the code to:

 miEntity.Add(regUserAddress);
 miEntity.SaveChanges();
Dave Swersky
I don't see any Add method. I don't want to insert a new record. I want to update selcted record.
Rita
+1  A: 

What Dave Said

+

You need to Attach() the disconnected entity to your object context:

http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attach.aspx

miEntity.Attach(regUserAddress);
miEntity.SaveChanges();
jfar
Hmm.... I tried to attach. Still getting the same error.
Rita
Are you sure the record is in the database? What is AD_id? The PK?
jfar
Yes. There is this record in the database.
Rita
A: 

First select the record (object entity) Search by key through the ObjectContext. For example if the search ArticleSet EntitySet called for there to record, and once you get it modified its properties with new values and then apply your SaveChanges () of ObjectContext. Example: ObjectQuery myArt=Context.ArticleSet.Where myArt = (row => row.ArticleId == value); myArt.Description=" new value "; etc. .. etc ... Context.SaveChanges ();

Claudio