开发者

Error while updating Database record with Entity Framework on ASP.NET MVC Page

开发者 https://www.devze.com 2022-12-22 15:22 出处:网络
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 my controller.

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 my controller.

When I am calling the ApplyPropertyChanges method, I am getting an 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:

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


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.


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


Just add the following code before miEntity.SaveChanges():

miEntity.Entry(regUserAddress).State = EntityState.Modified;


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 call SaveChanges() of ObjectContext.

Example:

ObjectQuery<Article> myArt=Context.ArticleSet.Where myArt = (row => row.ArticleId == value);
myArt.Description=" new value ";
etc. ..
etc ...

Context.SaveChanges ();
0

精彩评论

暂无评论...
验证码 换一张
取 消