views:

50

answers:

1

I'm trying to test detaching an entity from one context, making modifications to it, creating a new context, attaching it, and having the changes made between sessions persist. I don't seem to be able to get this working appropriately. I've tried calling DetectChanges as well as ApplyCurrentValues w/ no success. Below is what I've got so far. These aren't POCO's and I don't want to treat them as such. I just want to be able to detach an entity, make changes to it, and re-attach it. Thanks!

OCConsumer consumer;

using (var ctx1 = new CMSStagingContext())
{
    consumer = (from c in ctx1.OCConsumers
            select c).FirstOrDefault();

    Console.WriteLine("Retrieved {0} - {1} {2}",
        consumer.CustomerId, consumer.FirstName, consumer.LastName);

    ctx1.Detach(consumer);
}

consumer.BirthDate = "10/22/1981";

using (var ctx2 = new CMSStagingContext())
{
    ctx2.Attach(consumer);
    ctx2.ApplyCurrentValues("OCConsumers", consumer);
    ctx2.SaveChanges(System.Data.Objects.SaveOptions.DetectChangesBeforeSave | System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
}
A: 

When you attach an object to a context, the context is going to presume that the object is unmodified, unless you tell it otherwise. The simplest way to do this is to attach the object to the context first, then modify it. So you could change your code to:

OCConsumer consumer;

using (var ctx1 = new CMSStagingContext())
{
    consumer = (from c in ctx1.OCConsumers
            select c).FirstOrDefault();

    Console.WriteLine("Retrieved {0} - {1} {2}",
        consumer.CustomerId, consumer.FirstName, consumer.LastName);

    ctx1.Detach(consumer);
}

using (var ctx2 = new CMSStagingContext())
{
    ctx2.Attach(consumer);
    consumer.BirthDate = "10/22/1981";
    ctx2.SaveChanges(System.Data.Objects.SaveOptions.DetectChangesBeforeSave | System.Data.Objects.SaveOptions.AcceptAllChangesAfterSave);
}

Another approach would be to use Context.ObjectStateManager.ChangeObjectState.

Craig Stuntz
I was under the impression that DetectChanges in EF4 was supposed to do exactly this?
James Alexander
It detects changes *vs. the old version of the object in the context.* Which, in your case, is one and the same. See: http://msdn.microsoft.com/en-us/library/dd456854(VS.100).aspx
Craig Stuntz