This project has moved. For the latest updates, please go here.

Modifying entities outside of 'using' statement.

Feb 16, 2016 at 5:53 PM
Edited Feb 16, 2016 at 5:53 PM
I've been chasing my tail figuring out why the db is not being updated.

I use the recommended approach of a new context inside a using statement:
IThing thing = null;
                
using (var ctx = new KPEntityContext(KPEntityContext.DefaultConnectionString))
{
 thing = ctx.Things.Create();
 thing.Identifier = opcItem.Channel;
 thing.Kind = "[unset]";
 thing.AutoLearned = true;

 ctx.Things.Add(thing);

 ctx.SaveChanges();
}
Then later on inside the same method I was doing this:
using (var ctx = new KPEntityContext(KPEntityContext.DefaultConnectionString))
{
 var feature = ctx.Features.Create();
 feature.Identifier = opcItem.Id;
 feature.AutoLearned = true;
 feature.Owner = thing;

 thing.InternalFeatures.Add(feature);

 ctx.SaveChanges();
}
...and I could not figure out why thing.InternalFeatures collection was empty.
That's because I was modifying 'thing' outside of its original context...
Marked as answer by fixitchris on 2/16/2016 at 10:55 AM
Coordinator
Feb 23, 2016 at 5:32 PM
Yep that would do it. You would need to reattach the thing object to the new context, or for a cleaner experience I would recommend that between contexts you just hold on to the Id of thing and then reload it in the new context.