在ASP.NET MVC页面上使用实体框架更新数据库记录时出错 [英] Error while updating Database record with Entity Framework on ASP.NET MVC Page
问题描述
我有一个ASP.NET页面更新所选记录的注册用户地址详细信息。
以下是我从Controller调用的Update方法。
当我调用 ApplyPropertyChanges 方法时,我得到以下错误。
当使用Entity Framework更新记录时,有人遇到同样的错误。
欣赏您的回应。
错误讯息:
ObjectContext中的现有对象处于已添加状态。更改只能在现有对象处于未更改或修改状态时应用。
我的更新方法代码
[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? 主;
regUserAddress.Phone =((AddressDetail)Session [CurrentAddress])。
regUserAddress.Country =((AddressDetail)Session [CurrentAddress])。AddressType? 美国;
miEntity.ApplyPropertyChanges(regUserAddress.EntityKey.EntitySetName,regUserAddress);
miEntity.SaveChanges();
返回true;
}
>
+
您需要将断开的实体Attach()附加到对象上下文中:
http:/ /msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attach.aspx
miEntity.Attach(regUserAddress);
miEntity.SaveChanges();
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;
}
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();
这篇关于在ASP.NET MVC页面上使用实体框架更新数据库记录时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!