How to clean-up an Entity Framework object context?
- by Daniel Brückner
I am adding several entities to an object context.
try
{
forach (var document in documents)
{
this.Validate(document); // May throw a ValidationException.
this.objectContext.AddToDocuments(document);
}
this.objectContext.SaveChanges();
}
catch
{
// How to clean-up the object context here?
throw;
}
If some of the documents pass the the validation and one fails, all documents that passed the validation remain added to the object context. I have to clean-up the object context because it may be reused and the following can happen.
var documentA = new Document { Id = 1, Data = "ValidData" };
var documentB = new Document { Id = 2, Data = "InvalidData" };
var documentC = new Document { Id = 3, Data = "ValidData" };
try
{
// Adding document B will cause a ValidationException but only
// after document A is added to the object context.
this.DocumentStore.AddDocuments(new[] { documentA, documentB, documentC });
}
catch (ValidationException)
{
}
// Try again without the invalid document B.
this.DocumentStore.AddDocuments(new[] { documentA, documentC });
This will again add document A to the object context and in consequence SaveChanges() will throw an exception because of a duplicate primary key.
So I have to remove all already added documents in the case of an validation error. I could of course perform the validation first and only add all documents after they have been successfully validated. But sadly this does not solve the whole problem - if SaveChanges() fails all documents still remain add but unsaved.
I tried to detach all objects returned by
this.objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added)
but I am getting a exception stating that the object is not attached. So how do I get rid of all added but unsaved objects?