views:

75

answers:

1

Hello.

I am doing some testing with EF and i was trying to get a hook on the ObjectContext.SavingChanges. Everything works when i add objects directly to their set in the context. But when i add them through an Entity nav property they don't show up in the event.

I'll show an example to make it more clear. This is the method registered in the SavingChanges event.

void SavingChanges(object sender, System.EventArgs e)
{   var oc = (ObjectContext)sender;
    foreach (var entity in oc.ObjectStateManager
        .GetObjectStateEntries(EntityState.Added | EntityState.Deleted | EntityState.Unchanged | EntityState.Modified))
        Debug.WriteLine(entity);

}

And this is how i am adding stuff to the context.

var w1 = new Workspace()
             {
                 Name = "teste1",
             }; 

var w2 = new Workspace()
             {
                 Name = "teste2"
             }; 

var w3 = new Workspace()
             {
                 Name = "teste3"
             }; 

var w4 = new Workspace()
             {
                 Name = "teste4"
             }; 

//this shows up in the event
context.Workspaces.Add(w1);

//these do NOT show up on the event
w1.Children.Add(w2);
w1.Children.Add(w3);
w1.Children.Add(w4);

context.SaveChanges();

Is there a way i can get all the entities that were added in when the SaveChanges is called? They are being persisted in my database, so i want to know when it happens.

Thanks!

edit: i am using EF4 with CTP4.

edit2: This is my POCO.

public class Workspace
{
    public virtual int ID { get; set; }
    public virtual string Name { get; set; }  

    public virtual ICollection<Workspace> Children{ get;set;}

    public virtual Workspace Parent { get; set; }
}
A: 

Ok, so the problem was in the lack of change tracking. I was trying to use proxies to do just that but it turns out the 'new' operator does not create any kind of proxy, so no tracking is made to the objects and nothing added to them is added to the context.

To create a proxy I needed to call ObjectContext.CreateObject. Considering i was using DbContext the solutions were to either expose the internal ObjectContext or to create a method that would call the context internally. I went for the latter.

But this seems a hack. Do you have any suggestions for a more elegant solution?

Edit: Although this works it is possible to stick to the DbContext API only. This is done by using non-proxy POCOs and calling DetectChanges before the SavingChanges event is raised.

codegarten