2012-10-13 23 views
3

背景調試時可以看到ObjectStateManager中有什麼嗎?

我在EF中更新實體時遇到了一些麻煩。我不斷收到此錯誤:「具有相同鍵的對象已經存在於ObjectStateManager的ObjectStateManager無法跟蹤具有相同鍵的多個對象」

我完全知道,有明顯的另一個實體某處附上。但是,我目前無法追查。有很多代碼,我已經花了很多時間了。據我所見,我對所有查詢都使用AsNoTracking()擴展方法。

我需要什麼

我的問題是:有什麼辦法,我可以看到什麼是真正的ObjectStateManager在任何給定的時間?如果我可以在調試過程中看到那裏的物品,我可以更快地追蹤這些物品的來源。

如果上述不可能,我將不勝感激關於如何最好地解決這個問題的任何建議..它就像現在在乾草堆裏的針。

回答

1

這個問題幫助:

what is the most reasonable way to find out if entity is attached to dbContext or not?

,我實現了它這樣:

var attachedEntity = context.ChangeTracker.Entries<T>().FirstOrDefault(x => x.Entity.Id == entity.Id); 

       // If the entity is already attached. 
       if (attachedEntity != null) 
       { 
        // Set new values 
        attachedEntity.CurrentValues.SetValues(entity); 
       } 
       else 
       { 
        // Else attach the entity (if needed) 
        if (context.Entry(entity).State == EntityState.Detached) 
        { 
         Entities.Attach(entity); 
        } 
        // Set the entity's state to modified 
        context.Entry(entity).State = EntityState.Modified; 
       } 
       context.SaveChanges(); 

注:Entities只是IDbSet<T>context.Set<T>()和上面的代碼是從更新()方法在我的通用資源庫中。

0

這篇文章:http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2007/08/27/9656.aspx包含傾銷ObjectStateManager的內容的一些代碼。

here

Almost certainly what is happening here is that the object you are trying to delete is not attached, but a related entity or collection loaded on the detached instance is already attached to the ObjectContext. So when you try to attach the entity you are trying to delete, we try to attach the entire graph, which includes entities that are already attached.

這類問題是一個有點疼痛,所以在我的情況下,我嘗試,我可以做一個單一的using(Context context = new MyEntities())塊內儘可能多的活動,我可以。

另一條建議是在添加對象之前檢查對象是否已經存在。我知道很明顯,但過去我曾幾次絆倒過那個人。

+0

欣賞信息,謝謝..但看到我自己的答案,我是如何解決這個問題。 – Matt

1

Is there any way I can see what is actually in the ObjectStateManager at any given time? If I can see the items in there during debugging, I can more quickly track down where this is coming from.

您還可以使用Visual Studio調試器的快速監視功能查看ObjectStateManager中的內容。路徑是:

context -> ObjectContext -> ObjectStateManager -> Non-Public members

0

經常被忽略:Context.Set<T>.Local()它只提供相關類型的附加實體。

相關問題