1

我正在尝试更新 CustomerRailcard 对象,该对象对 Railcard 对象的引用以 end * 为 1。问题是,我无法删除 Railcard 对象,我只需将 CustomerRailcard 对象上的引用更改为另一个 RailcardObject。我这样做是这样的:

更新:

// Updating properties in existing CustomerRailcard. 
// This won't update navigation properties (Railcard).
context.ObjectStateManager.ChangeObjectState(existingCustomerRailcard, EntityState.Modified);
context.ApplyCurrentValues("CustomerRailcardsDbo", newCustomerRailcard);

// Now I'm trying to update navigation property of CustomerRailcard to the Railcard
// by removing the reference from old Railcard to CustomerRailcard. 
// Railcard can have references to many CustomerRailcards.
var oldRailcard = railcardRepository.FindById(customerDetails.CustomerRailcards.FirstOrDefault(r => r.Id == railcard.Id).Railcard.Id);
var customerRailcardToRemove = oldRailcard.CustomerRailcards.FirstOrDefault(cr => cr.Id == railcard.Id);

// Removing reference to CustomerRailcard from Railcard
oldRailcard.CustomerRailcards.Remove(customerRailcardToRemove);


// Now I'm getting new Railcard I want to have referenced by CustomerRailcard
// and I'm changing its reference tu CustomerRailcard
var newRailcard = railcardRepository.FindById(railcard.Railcard.Id);

// Adding reference to CustomerRailcard
newRailcardDboReference.CustomerRailcards.Add(railcard);

运行后我会得到这个错误

来自“CR_RL_FK”关联集的关系处于“已删除”状态。给定多重约束,相应的“CustomerRailcardDbo”也必须处于“已删除”状态。

我还应该如何对这种关系进行更新?

4

1 回答 1

1

从导航属性中删除是不够customerReilcardToRemove的 - 只会破坏关系但不会删除CustomerReilcard实例。您的关系需要CustomerReilcard具有主体Reilcard,因此您必须customerReilcardToRemove通过调用删除实例DeleteObject或使关系可为空并保留孤立实例。

于 2012-08-13T19:13:58.273 回答