0

I have an EF model where I have set lazy loading to true. I do this query:

public static WorkflowStatus Get(int id)
{
    WorkflowStatus status;
    using (var db = new WorkflowDb())
    {
        status = db.WorkflowStatuses
            .Include("CurrentMappings")
            .Include("CurrentMappings.NextWorkflowStatus")
            .Include("NextMappings")
            .Include("NextMappings.CurrentWorkflowStatus")
            .Include("WorkQueueWorkflowStatusMaps")
            .Include("WorkQueueWorkflowStatusMaps.WorkQueue")
            .FirstOrDefault(x => x.Id == id);
    }
    return status;
}

After I get the status back there is more than just those things being populated. For example each WorkQueueWorkflowStatusMap has a WorkQueue and WorkQueue has a collection of WorkQueueWorkflowStatusMaps - so there is an infinite amount of back and forth being loaded. How do I get that to stop? When I return this through a WCF service in another layer it throws an exception because of this.

Rush Frisby
  • 11,388
  • 19
  • 63
  • 83

3 Answers3

2

How to stop EF from loading entire object graph?

By all those includes you told EF to load whole object graph. Every include says: load this relation as well.

so there is an infinite amount of back and forth being loaded

No. Entities are loaded only once. What you see is circular reference which is included in your model. If your WorkQueueWorkflowStatusMap has WorkQueue navigation property and in the same time WorkQueue has WorkQueueWorkflowStatusMap navigation property than you modeled circular reference which is absolutely correct until you try to serialize your entity = problem in WCF. In such case you must inform serializer that circular references are used.

If you want to use serialization and WCF you should follow @Eranga's deleted answer - turn off lazy loading and proxy creation.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • Setting the properties from the deleted post did not work but from reading your linked answer I tried modifying the t4 template with DataContract[IsReference=true] and that works perfectly. Thanks! – Rush Frisby Dec 16 '11 at 17:30
0

Stop deep loading by add .AsNoTracking()

db.WorkflowStatuses.Include(s => s.childObject)
             .AsNoTracking()
Amr Ibrahim
  • 2,066
  • 2
  • 23
  • 47
0

From Getting Started with Entity Framework 4 – Lazy Loading:

context.ContextOptions.LazyLoadingEnabled = true;
DaveB
  • 9,470
  • 4
  • 39
  • 66
  • 1
    "I have an EF model where I have set lazy loading to true." – Rush Frisby Dec 16 '11 at 01:04
  • The lazy loading works fine. I think it has something to do with having already loaded everything in the back-and-forth that causes it to spiral out of control with the references. – Rush Frisby Dec 16 '11 at 01:10