我真的希望有人可以帮助我。我有以下控制器动作:
public ActionResult Edit(EditViewModel vm)
{
Item item= db.Items.Find(vm.ItemId);
if (ModelState.IsValid)
{
//breakpoint 1 --> everything works fine, if its debugged step by step from here
//if item´s contact is null or different from viewmodel --> override it
if (item.Contact == null || item.Contact.ContactId != vm.ContactId)
item.Contact = db.Contacts.Find(vm.ContactId);
//if the viewmodel have a ContractUnit set and its different from item´s --> override the contractunit
//is the ContractUnit in viewmodel null set item´s null too
if (vm.ContractUnitId.HasValue && ((item.ContractUnit != null && item.ContractUnit.ContractUnitId != vm.ContractUnitId) || item.ContractUnit == null))
item.ContractUnit = db.ContractUnits.Find(vm.ContractUnitId);
else
if (!vm.ContractUnitId.HasValue)
item.ContractUnit = null;
//same as above just for Building
if (vm.BuildingId.HasValue && ((item.Building != null && item.Building.BuildingId != vm.BuildingId) || item.Building == null))
item.Building = db.Buildings.Find(vm.BuildingId);
else
if (!vm.BuildingId.HasValue)
item.Building = null;
//same as above just for EconomicUnit
if (vm.EconomicUnitId.HasValue && ((item.EconomicUnit != null && item.EconomicUnit.EconomicUnitId != vm.EconomicUnitId) || item.EconomicUnit == null))
item.EconomicUnit = db.EconomicUnits.Find(vm.EconomicUnitId);
else
if (!vm.EconomicUnitId.HasValue)
item.EconomicUnit = null;
//breakpoint 2 --> (no changes to item, if its the first breakpoint)
item= vm.GetItem(item); //override non relational data
db.Entry(item).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
...
}
来自EditViewModel的方法GetItem:
public Item GetItem(Item item)
{
item.DateReported = this.DateReported; //Datetime
item.Description = this.Description; //String
item.FirstDeadline = this.FirstDeadline; //Datetime
item.SecondDeadline = this.SecondDeadline; //Datetime
item.ThirdDeadline = this.ThirdDeadline; //Datetime
item.ReplacementDeadline = this.ReplacementDeadline; //Datetime
return item;
}
问题:EF没有将更改保存到item.Building,item.ContractUnit或item.EconomicUnit。但它确实在我一步一步地调试它。 抛出没有错误或异常,并且正确填充了viewmodel和model。
我真的希望有人能帮我解决这个问题......
答案 0 :(得分:0)
我从项目模型中移除了关系,现在只将ids保存在" long?"属性。那么,它现在需要额外的工作来获取相关数据,但至少它可以工作。
答案 1 :(得分:0)
尝试拨打
DBSet.Attach(entityToUpdate);
之前
db.Entry(item).State = EntityState.Modified;
也许这有帮助。