I have a class that contains objects of another class:
public class Container
{
public BindingList<Item> Items { get; set; }
}
public class Item
{
...
}
Objects of the Container are attached to a DbContext. I want to override the DbContext's SaveChanges() to send all changes via a WCF service.
Primitive attributes are no problem. They are reflected in the Entries. But if the relationship between an Item and its Container changes (e.g. a new item is added or an existing item is deleted) there is no entry about that in the ChangeTracker.
I could add a ForeignKey in the Item class to force a Modified entry, but this does not help me much, because I need to know the containing object.
I also tried to convert the DbContext to ObjectContext to get all related items of an entity. But I see no way to get the actual object of a RelatedEnd.
Is there a way to track changes of the contained collection?
Update
As requested, some code I already have:
//In a DbContext subclass
public override int SaveChanges()
{
//get all modified entities
var changes = this.ChangeTracker.Entries();
foreach (var c in changes)
{
//check the state of the entity
switch (c.State)
{
//send according WCF callback to the clients
case System.Data.EntityState.Added:
App.Current.ServerManager.SendEvent(s => s.EntityAdded((IIdentifiable)c.Entity), causedBy);
break;
...
}
}
return base.SaveChanges();
}
With this code, I cannot detect changes of the Items collection.
Take a look at this question it shows how to get added relationships. Hopefuly it will help you get what you need.