I am using Entity Framework in .NET 4.0. I have a Subscription object that has many CFile objects. I am creating a new CFile , but I am not really calling it AddObject . Later, I try to save the Subscription object that is associated with it, and EF tries to save the CFile instance that I never planned!
Simplified code:
var subscription = new Subscription(); Context.Subscription.AddObject(subscription); Context.SaveChanges(); var cfile = new CFile() { Subscription = subscription }; if (SomeChecksPass(cfile)) { Context.CFiles.AddObject(cfile); } else {
I understand why this is happening, but how can I get him not to do this? This creates a rather subtle and incomprehensible error (the real code is obviously much more complicated). I want it to save only objects that I explicitly passed to AddObject .
I also know about a Detach : call Detach on an entity that I don't want to save. However, this is not a good workaround, because I have to make sure that I call Detach in all possible codes where CFile not saved (and in some codes it is saved), so it should be called after this solution but before anything still be preserved. It is very fragile, and I really do not want to rely on it.
Edit: CFile is created because I want to save it most of the time, but if some verification fails or some error occurs, I do not. I still want to save some changes to the Subscription object.
source share