实体框架更新对象和更改引用

时间:2012-08-13 15:29:55

标签: c# entity-framework-4

我试图对CustomerRailcard对象进行更新,该对象对Railcard对象有一个引用,结尾为* 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'的关系AssociationSet位于'已删除'州。鉴于多重性限制,相应的“CustomerRailcardDbo”#39;还必须在“删除”中删除。状态。

我还应该如何处理这种关系的更新?

1 个答案:

答案 0 :(得分:1)

仅从导航属性中删除customerReilcardToRemove是不够的,而不仅仅是中断关系但不删除CustomerReilcard实例。您的关系要求CustomerReilcard拥有主体Reilcard,因此您必须通过调用customerReilcardToRemove删除DeleteObject实例,或者使关系成为可空并保留孤立实例。