0

我正在使用带有 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);
}

我不知道为什么我要处理这种错误。请问有什么办法解决这个问题吗?

4

2 回答 2

5

交通,

简短的回答,你应该删除这 2 行

 db.VehicleTypes.Attach(vehicleType);
 db.ProductTypes.Attach(productType);

当您从 EntityFramework 实例检索任何实体并修改任何属性时,Entity Framework 会自动跟踪更改。

要将更改应用于数据库,您只需调用

db.SaveChanges();

要更好地了解何时使用 Add 和 Attach 方法,您应该阅读此 Entity Framework 4 - AddObject vs Attach

我希望它有所帮助。

于 2013-04-19T13:07:45.810 回答
0

只需删除“附加”,因为对象已经在数据库中,无需再次附加,只需更改状态并保存更改

 var comp = (from com in db.tbl_CompGroup where com.Group_Id == GroupID select com).FirstOrDefault();

        comp.Survey_Est = surveyPost.Survey_Est;

        //db.tbl_CompGroup.Attach(comp);
        db.ObjectStateManager.ChangeObjectState(comp, System.Data.EntityState.Modified);
        db.SaveChanges();
于 2016-05-11T09:28:57.340 回答