0

HI I have a project with uses EF self tracking objects.I am trying to add a relationship to an object . (parentobject.relationshipObject.Add(New relationshipObject...)). But it throws an error:

Cannot change ObservableCollection during a CollectionChanged or PropertyChanged event.

This error occurs in the #Region "Association Fixup" of the code created by the template. Initially the mainobject does not bring any relationship. Only when the item is selected by the user the relationships are updated in the item. i found that if i remove the MainObject from the collection and readd it with the relationships this error does not occur. if i only update the relationship object in the mainObject , this issue occurs when i add a new relationship object from the client side any help is much appreciated

--code sequence is as follows 1. get all the parent entities. 2. when user select an entity get the relationship of the entity and update the relationship entity

parentCol.AsEnumerable.Where(Function(x) x.ID = e.Result.ID).FirstOrDefault().StopTracking() parentCol.AsEnumerable.Where(Function(x) x.ID = e.Result.ID).FirstOrDefault().relationshipEntity = e.Result.relationshipEntity parentCol.AsEnumerable.Where(Function(x) x.ID = e.Result.ID).FirstOrDefault().StartTracking()

  1. to add a new item in the relationEntity

Dim newRel As New relationshipEntity newRel.Ref_parent_Id = parentItem.ID newRel.REF_rel_ID = relItem.Id parentItem.relationshipEntity.Add(newRel) ---> Throws error here

the relationshipEntity denotes the relationship table between the parent entity and another entity (many to many relationship).

thanks

user55474
  • 537
  • 1
  • 8
  • 25

1 Answers1

0

Are you trying to add a new child while setting the child's parent?

Since EF tries to fix up one way links on two way relationships, I assume this could cause such an issue.

E.g.

parent.Add(new Child { Parent = parent, Name = "abc" });

As opposed to letting EF do the other side of the connection

parent.Add(new Child { Name = "abc" });

or

new Child { Parent = parent, Name = "abc" });
Danny Varod
  • 17,324
  • 5
  • 69
  • 111
  • Could you detail the steps you see in the debugger until exception is thrown and the state before debugging. – Danny Varod Apr 18 '11 at 07:44
  • as u had suggested EF is trying to remove the relationship and readd it. when it tries to remove the relationship the error is thrown. However if i remove and readd the parent entity and then add the relationship object it works fine. – user55474 Apr 18 '11 at 21:25
  • A simple before and after example may help others avoid the problem. (You could post it as an answer to your question.) – Danny Varod Apr 19 '11 at 12:53