我正在使用带有 MVC 4 的实体框架来开发 Web 应用程序。我还使用了一个名为 VehicleTypeViewModel 的 ViewModel,它的创建方式如下:
public class VehicleTypeViewModel
{
public VehicleType VehicleType { get; set; }
public ProductType ProductType { get; set; }
[RegularExpression(@"^[a-zA-Zàéèêçñ\s][a-zA-Zàéèêçñ\s-]+$", ErrorMessage = "Invalid name !")]
public string Name { get; set; }
[Range(0, 300)]
public int CO2 { get; set; }
public List<SelectListItem> ProductCompanies { get; set; }
public List<SelectListItem> MotorTypes { get; set; }
}
在我的编辑操作中,一切都很好,但只有一件事:当我调试时,到达db.Attach(...)
步骤时,我的应用程序抛出一个异常,它说:
The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state.
这是我的帖子操作:
[HttpPost]
public ActionResult Edit(VehicleTypeViewModel vtvm)
{
ViewBag.Id_VehicleMotorType = new SelectList(db.VehicleMotorTypes, "Id_VehicleMotorType", "Name", vtvm.VehicleType.Id_VehicleMotorType);
ViewBag.Id_ProductCompany = new SelectList(db.ProductCompanies, "Id_ProductCompany", "Name", vtvm.ProductType.Id_ProductCompany);
vtvm.ProductCompanies = db.ProductCompanies.ToList().Select(c => new SelectListItem { Text = c.Name, Value = c.Id_ProductCompany.ToString() }).ToList();
vtvm.MotorTypes = db.VehicleMotorTypes.ToList().Select(v => new SelectListItem { Text = v.Name, Value = v.Id_VehicleMotorType.ToString() }).ToList();
VehicleType vehicleType = db.VehicleTypes.Single(v => v.Id_VehicleType == vtvm.VehicleType.Id_VehicleType);
ProductType productType = db.ProductTypes.Single(p => p.Id_ProductType == vtvm.ProductType.Id_ProductType);
VehicleMotorType vehicleMotorType = null;
ModelStateDictionary errors = Validator.isValid(vtvm.ProductType);
if (ModelState.IsValid)
{
if (errors.Count > 0)
{
ModelState.Merge(errors);
return View(vtvm);
}
productType.Model = vtvm.ProductType.Model;
productType.CatalogPrice = vtvm.ProductType.CatalogPrice;
productType.Id_ProductCompany = vtvm.ProductType.Id_ProductCompany;
if (!string.IsNullOrWhiteSpace(vtvm.Name) && (vtvm.CO2 > 0))
{
vehicleMotorType = new VehicleMotorType()
{
CO2 = vtvm.CO2,
Name = vtvm.Name
};
vehicleType.CO2 = vtvm.VehicleType.CO2;
vehicleType.VehicleMotorType = vehicleMotorType;
vehicleType.Id_ProductType = vtvm.ProductType.Id_ProductType;
}
else
{
vehicleType.CO2 = vtvm.VehicleType.CO2;
vehicleType.Id_ProductType = vtvm.ProductType.Id_ProductType;
vehicleType.Id_VehicleMotorType = vtvm.VehicleType.Id_VehicleMotorType;
}
db.VehicleTypes.Attach(vehicleType);
db.ProductTypes.Attach(productType);
db.ObjectStateManager.ChangeObjectState(vehicleType, EntityState.Modified);
db.ObjectStateManager.ChangeObjectState(productType, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(vtvm);
}
我不知道为什么我要处理这种错误。请问有什么办法解决这个问题吗?