Reputation: 414
I'm trying to make update on CustomerRailcard object which has a reference on Railcard object with end * to 1. The problem is, that I cannot delete Railcard object, I have to only change reference on CustomerRailcard object to another RailcardObject. I'm doing it like this:
UPDATE:
// 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);
After running this I'll get this error
A relationship from the 'CR_RL_FK' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'CustomerRailcardDbo' must also in the 'Deleted' state.
How else should I perform update on this kind of relationship?
Upvotes: 1
Views: 1101
Reputation: 364249
It is not enough to remove customerReilcardToRemove
from the navigation property - than only breaks relation but does not delete the CustomerReilcard
instance. Your relationship requires that CustomerReilcard
has a principal Reilcard
so you must either delete customerReilcardToRemove
instance by calling DeleteObject
or make the relation nullable and keep orphan instances.
Upvotes: 1