开发者

Entity framework: detaching but keeping object graph

开发者 https://www.devze.com 2023-01-21 04:22 出处:网络
I\'m working in a disconnected scenario, but I noticed that disposing an object context does not release attached entities. As a result, subsequent operations often fail because of this.

I'm working in a disconnected scenario, but I noticed that disposing an object context does not release attached entities. As a result, subsequent operations often fail because of this.

So to solve this, I detach everything myself when the object context is being disposed:

public void Dispose()
{
   // detaching is not really needed, because开发者_开发知识库 we have short living object contexts
   var objectStateEntries = 
       _context.UnderlyingContext.ObjectStateManager.GetObjectStateEntries(EntityState.Unchanged);           
   objectStateEntries.ToList().ForEach(o => { if (o.Entity != null)
   {                
     _context.UnderlyingContext.Detach(o.Entity);               
   }});            

   _context.Dispose();
   _context = null;    
}

However, the side effect is that the object graph gets detached completely, but I really want to keep the graph!

It seems I don't find a solution for this, is it true that it can't be done?


We had this problem as well; you cannot have part of a graph attached to an EF context. Have you considered loading up data initially in a detatched state? The context is then used as a stateless repository of data and nothing else.

You can load up data as detatched initially as follows:

myDataContext.MyEntitySet.MergeOption = MergeOption.NoTracking;
0

精彩评论

暂无评论...
验证码 换一张
取 消