如何清理实体框架对象上下文? [英] How to clean-up an Entity Framework object context?
问题描述
我添加几个实体对象上下文。
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 causes an exception because
// of a duplicate primary key - document A with id 1 is added a second time.
this.DocumentStore.AddDocuments(new[] { documentA, documentC });
这将再次文件A添加到对象上下文,并在后果的SaveChanges( )
将抛出,因为重复的主键的一个例外。
This will again add document A to the object context and in consequence SaveChanges()
will throw an exception because of a duplicate primary key.
所以,我必须删除所有已添加的文档在验证错误的情况下, 。我当然可以先进行验证和只添加的所有文件后,他们已经被成功验证,但可悲的是这并没有解决整个问题 - 如果的SaveChanges()
失败,所有的文件仍保持增加,但尚未保存的。
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 added but unsaved.
我企图吞并由
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?
推荐答案
这只是一个微不足道的错误,但我要离开这里的问题 - 也许它可以帮助别人
It was just a trivial bug but I am going to leave the question here - maybe it helps others.
我有以下
var objectStateEntries = this.objectContext
.ObjectStateManager
.GetObjectStateEntries(EntityState.Added);
foreach (var objectStateEntry in objectStateEntries)
{
this.objectContext.Detach(objectStateEntry);
}
而我想以下
while I wanted the following
foreach (var objectStateEntry in objectStateEntries)
{
this.objectContext.Detach(objectStateEntry.Entity);
}
和无法看到它。
这篇关于如何清理实体框架对象上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!