Entity Framework - Detach and keep related object graph

entity-framework

Question

I've just started using Entity Framework rather than my normal NHiberante to see how EF works and so far I'm having lots of problems but one in particular is detaching an object and keeping the related child objects.
I bought the O'Reilly Entity Framework book which tells you "yes entity framework by default doesn't keep the object graph when you detach" but it doesn't show how you how to keep the graph! Thanks O'Reilly thats really useful.

Anyway if anyone can help that would be great, code below:

        using (var creativeWorkshopEntities = new CreativeWorkshopEntities())
        {
            var q = from c in creativeWorkshopEntities.Job.Include("Files")
                    where c.Id == jobId
                    select c;

            var job = q.First();

            creativeWorkshopEntities.Detach(job);

            return job;
        }

Thanks!

Dan

Popular Answer

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)



Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why