Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework - Detach and keep related object graph

Try using a NoTracking query instead. That way the objects arenever attached, so you don't need to 'detach' which is when the graph is shredded:

i.e.

using (var creativeWorkshopEntities = new CreativeWorkshopEntities())        
{            
    creativeWorkshopEntities.Job.MergeOption = MergeOption.NoTracking;
    var q = from c in creativeWorkshopEntities.Job.Include("Files")
            where c.Id == jobId                    
            select c;            
    var job = q.First();            
    return job;
} 

Hope this helps

Alex

(Program Manager Entity Framework Team)


In EF5 the MergeOption is not at the DbSet level anymore. So according to this: http://msdn.microsoft.com/en-us/data/hh949853.aspx

If you want to do a not tracking query you will need to do something like:

  var q = from c in creativeWorkshopEntities.Job.AsNoTracking().Include("Files")
                        where c.Id == jobId
                        select c;

Check out http://www.codeproject.com/KB/architecture/attachobjectgraph.aspx

This is an awesome solution and may help you out - be aware that the author has an updated version on his own blog too - http://www.codetuning.net/blog/post/Entity-Framework-reattaching-entity-graphs-(3).aspx

Paul