MadKian88
MadKian88

Reputation: 162

EF code first circular reference

I have a question about Entity Framework. In our project we would need to have some circular references, like this one:

public class OptionClusterSet
{
    public int ID { get; set; }

    public virtual ICollection<OptionCluster> OptionClusters { get; set; }
}

public class OptionCluster
{
    public int ID { get; set; }

    public long OptionClusterSetId { get; set; }

    public virtual OptionClusterSet OptionClusterSet { get; set; }
}

The thing is that whenever we try to, for example, get a OptionClusterSet including its OptionClusters using eager loading, the OptionClusters try to load their OptionClusterSets and so on. So we get an infinite loop.

Is there a way to configure this so it works properly?

Upvotes: 2

Views: 1026

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364279

It works properly out of the box unless you try to serialize it - serialization needs some special handling (attributes) to let serializer recognize circular reference.

Eager loading loads only the level you specify in Include call, nothing more. Everything else can be loaded through lazy loading but EF don't load again the relation which was already loaded. There are some scenarios when it doesn't work as expected - the example is navigation property fixup in POCO generator (it lazy loads additional data to fixup the reverse navigation property).

Upvotes: 1

Related Questions