(Note: I see this, but it’s not exactly what I want to do.)
I have a requirement where I need to do the following:
- Create a new
Fooentity - Upon creation of a Foo entity, create a new
FooAuditentity and use the new identity value from the newFooentity in the text description.FooAudithas no reltionship with Foo, so the identity must be pulled manually from the creation ofFoo. - Do these things in an all-or-nothing transaction, keeping the
EntityStateof theFoorecord (Added) if I do not commit the transaction.
Do I use another context like so?
using (var fooContext = GetContext())
{
fooContext.Foos.AddObject(new Foo());
using (var transaction = new TransactionScope())
{
// Save Foo, while maintaining the Changed EntityState until AcceptAllChanges
fooContext.SaveChanges(SaveOptions.DetectChangesBeforeSave);
using (var auditContext = GetContext())
{
// Save FooAudit, maintaining the Changed EntityState until AcceptAllChanges
auditContext.FooAudits.AddObject(new FooAudit());
auditContext.SaveChanges(SaveOptions.DetectChangesBeforeSave);
transaction.Complete();
fooContext.AcceptAllChanges();
auditContext.AcceptAllChanges();
}
}
}
Or is there a better way?
I solved this by using another context as illustrated.