此問題可能看起來像其他類似問題的重複。但是,我建議你直到最後閱讀問題,然後決定它是否重複某個帖子或不是?操作失敗:由於一個或多個外鍵屬性不可空,因此無法更改關係。
我在我的數據庫6張桌子如下:
我已經插入所有表中的一些記錄。
現在,我正在嘗試更新訂單。
起初,我只是想更新的順序如下:
CurrentOrder.UpdateOrder(Order);
在OrderClient的UpdateOrder方法是這樣的:
public Order UpdateOrder(Order Order)
{
IOrderRepository OrderRepository = _DataRepositoryFactory.GetDataRepository<IOrderRepository>();
Order updatedEntity = null;
if (Order.OrderId == 0)
{
updatedEntity = OrderRepository.Add(Order);
}
else
{
updatedEntity = OrderRepository.Update(Order);
}
return updatedEntity;
}
而且在OrderRepository:
protected override Order UpdateEntity(RateDifferenceContext entityContext, Order entity)
{
return (from e in entityContext.OrderSet
where e.OrderId == entity.OrderId
select e).FirstOrDefault();
}
然後在DataRepositoryBase類中使用下面的方法:
public T Update(T entity)
{
using (U entityContext = new U())
{
T existingEntity = UpdateEntity(entityContext, entity);
SimpleMapper.PropertyMap(entity, existingEntity);
entityContext.SaveChanges();
return existingEntity;
}
}
在這一點上,我得到了一個錯誤說:
Multiplicity constraint violated. The role '…' of the relationship '…' has multiplicity 1 or 0..1
所以,我認爲我需要刪除其特定於所有相關的表的順序記錄。所以,我想下面的代碼:
using (var xaction = new TransactionScope())
{
foreach (OrderItemDetail orderItemDetail in OrderItemDetailClient.GetAllOrderItemDetails().Where(x => x.OrderId == NewOrder.OrderId))
{
OrderItemDetailClient.DeleteOrderItemDetail(orderItemDetail);
}
foreach (Dispatch dispatch in DispatchClient.GetAllDispatches().Where(x => x.OrderId == NewOrder.OrderId))
{
foreach (DispatchItemDetail dispatchItemDetail in DispatchItemDetailClient.GetAllDispatchItemDetails().Where(x => x.InvoiceId == dispatch.InvoiceId))
{
DispatchItemDetailClient.DeleteDispatchItemDetail(dispatchItemDetail);
}
DispatchClient.DeleteDispatch(dispatch);
}
OrderClient.UpdateOrder(NewOrder);
xaction.Complete();
}
現在,我得到另一個錯誤,說:
The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
我得到下面提到線這個錯誤在最後的代碼塊:
DispatchClient.DeleteDispatch(dispatch);
謝謝你的一個很好的解釋。我已經得到了我的答案。 – Vishal