2

In the constructor of each of my POCO's I have this:

this.StartTracking();

To ensure that tracking is turned on for every instance of one of my POCO's. I have an Entity A which contains a TrackableCollection of Entity B. When I load my instance of Entity A like such:

using(MyContext ctx = new MyContext())
{
    entityA = ctx.EntityA.Include("EntityB").Where(x => x.Id== id).FirstOrDefault();
}

Looking at the ObjectsAddedToCollection property on Entity A, there is 1 object flagged as 'Unchanged'. When I do entityA.EntityB[0].MarkAsDeleted(), the state does not get set to 'Deleted' and moved to the ObjectsRemovedFromCollection collection. It just gets removed altogether. I double checked and the ChangeTrackingEnabled is set to True for both Entity A and Entity B. Is there a reason why this is not working? Because of this I cannot delete child entity and persist the changes to the database.

Brandon
  • 10,744
  • 18
  • 64
  • 97

2 Answers2

2

This appears to be a bug. In the method RecordRemovalFromCollectionProperties I changed the line that simply returns to:

if(((IObjectWithChangeTracker) value).ChangeTracker.State == ObjectState.Added)
    return;

This fixed the issues I was having.

Brandon
  • 10,744
  • 18
  • 64
  • 97
0

Pretty dangerous though by changing this generated code. What the RecordRemovalFromCollectionProperties method does is to see if there are added objects that are removed again (final state = no entities added or removed, the adding and removal "strike out each other", you see...?). That's why there's also a RecordAdditionToCollectionProperties which does the "inverse" check of what I explained before.

Now, with your change to this method of the ChangeTracker it could be possible that you will sent away an EntityA that has an added EntityB and a removed EntityB (which are the same instances). This could be done by a user or by code someway.

I don't know if the object context will allow this at first. But it's at least a little inefecient. Sending an updated EntityA which says to the object context (context.ApllyChanges(EntityA)) Add this EntityB and immediately afterwards, mwoah remove this same EntityB also ;)

I have some experience in this field, so If you have further questions...

I think the original problem has a reason, but that your solution is a little rough.

Youp Bernoulli
  • 5,303
  • 5
  • 39
  • 59