Aeptitude
Aeptitude

Reputation: 312

Entity Framework related entities instantiating eachother and caught in endless loop

I have 2 classes within my context, they are as follows;

    public class Supplier
    {
        public int ID { get; set; }
        public virtual ICollection<SupplierOffice> SupplierOffices { get; set; }
    }

    public class SupplierOffice
    {
        public int ID { get; set; }
        public int SupplierID { get; set; }
        public virtual Supplier Supplier { get; set; }

    }       

The relationship is, a supplier has zero or many supplier offices

This context works as expected for the most part; when I want to get a supplier by ID, it returns the supplier populated with all of it's offices

However, what might be a problem is, when I inspect this code in the debugger;

So from what I can tell the system is loading the suppliers and the supplier offices endlessly in a loop. I don't think this is causing any performance issues, so I'm wondering if this is just a quirk of the debugger, and the actual system doesn't do this. If this is looping endlessly, how can I correct this?

Many thanks

Upvotes: 0

Views: 59

Answers (1)

MarkusEgle
MarkusEgle

Reputation: 3065

When you navigate in your Debugger, it is nothing else like you are using the navigation property when you are coding:

curSupplier.SupplierOffices 

then e.g.

curSupplier.SupplierOffices[0].Supplier 

then

curSupplier.SupplierOffices[0].Supplier.SupplierOffices

then

curSupplier.SupplierOffices[0].Supplier.SupplierOffices[1].Supplier

There is no recursion here and no endless loop. You are just using the navigation properties, and yes you could use them endless... As the navigation properties are in both directions you could do that and there will be no problem.

As Adriano Repetti wrote in the comments you are always inspecting/accessing the same supplier instance.

Upvotes: 1

Related Questions