提交出错:操作失败: 无法更改关系,因为一个或多个外键属性不可以为 null。对关系作出更改后,会将相关的外键属性设置为 null 值。如果外键不支持 null 值,则必须定义新的关系,必须向外键属性分配另一个非 null 值,或必须删除无关的对象。
//处理入库计划状态 if (partsPlannedWarehouseOrder != null) { foreach(var detail in partsPlannedWarehouseOrder.PartsInPlanOrderDetails.Where(p => p.PlannedQuantity == 0).ToArray()) //partsPlannedWarehouseOrder.PartsInPlanOrderDetails.Remove(detail); this.ObjectContext.PartsInPlanOrderDetails.DeleteObject(detail); if (!partsPlannedWarehouseOrder.PartsInPlanOrderDetails.Any()) partsPlannedWarehouseOrder.Status = (int)DmsPartsPlannedOrderStatus.作废; else if (partsPlannedWarehouseOrder.PartsInPlanOrderDetails.All(p => p.PlannedQuantity == p.CompletedQuantity)) partsPlannedWarehouseOrder.Status = (int)DmsPartsPlannedOrderStatus.完成; else if (partsPlannedWarehouseOrder.PartsInPlanOrderDetails.All(p => p.CompletedQuantity == 0)) partsPlannedWarehouseOrder.Status = (int)DmsPartsPlannedOrderStatus.生效; else partsPlannedWarehouseOrder.Status = (int)DmsPartsPlannedOrderStatus.部分完成; UpdateToDatabase(partsPlannedWarehouseOrder); UpdatePartsPlannedWarehouseOrderValidate(partsPlannedWarehouseOrder); } //处理出库计划状态 if (partsPlannedDeliveryOrder != null) { foreach(var detail in partsPlannedDeliveryOrder.PartsOutPlannOrderDetails.Where(p => p.PlannedQuantity == 0).ToArray()) // partsPlannedDeliveryOrder.PartsOutPlannOrderDetails.Remove(detail); this.ObjectContext.PartsOutPlannOrderDetails.DeleteObject(detail); if (!partsPlannedDeliveryOrder.PartsOutPlannOrderDetails.Any()) partsPlannedDeliveryOrder.Status = (int)DmsPartsPlannedOrderStatus.作废; else if (partsPlannedDeliveryOrder.PartsOutPlannOrderDetails.All(p => p.PlannedQuantity == p.CompletedQuantity)) partsPlannedDeliveryOrder.Status = (int)DmsPartsPlannedOrderStatus.完成; else if (partsPlannedDeliveryOrder.PartsOutPlannOrderDetails.All(p => p.CompletedQuantity == 0)) partsPlannedDeliveryOrder.Status = (int)DmsPartsPlannedOrderStatus.生效; else partsPlannedDeliveryOrder.Status = (int)DmsPartsPlannedOrderStatus.部分完成; UpdateToDatabase(partsPlannedDeliveryOrder); UpdatePartsPlannedDeliveryOrderValidate(partsPlannedDeliveryOrder); }
修改方法:用DeleteObject 方法代替Remove方法
例如://partsPlannedWarehouseOrder.PartsInPlanOrderDetails.Remove(detail);
this.ObjectContext.PartsInPlanOrderDetails.DeleteObject(detail);
不能修改正在遍历的集合,所以用remove是错的
DeleteObject只是将集合中的实体添标记为删除,并不是将实体移除集合,而是将实体添标记为EntityState.Deleted