Circular Reference with Include in .NET Core

.net-core entity-framework-core

Question

I am using code like below in .NET core

.Include(p => p.Company).ThenInclude(p => p.Country).ToList();

My classes look like below,


 public partial class Company
    {
        public Guid Id { get; set; }
        public string Name { get; set; }

        public virtual Country Country { get; set; }
    }

     public partial class Country
    {
      public Country()
        {

            Companies = new HashSet<Company>();
        }

        public Guid Id { get; set; }
        public string Name { get; set; }
         public string ShortCode { get; set; }

          public virtual ICollection<Company> Companies { get; set; }
    }

And I want only Company and then Country in side the company to be populated. But I am getting the Company inside the Country and then Country in those Companies and so on populated which is causing the response delayed.

I have already tried difference examples of Include on Google/StackOverFlow.

1
0
9/6/2019 8:27:55 AM

Popular Answer

This isn't actually a problem. EF has what's called "object fix-up". Internally, it uses an object cache. When it builds entity instances for database query results, it adds those to the object cache, allowing it to then pull out those objects later, rather than issuing the same queries again.

Because of this object cache, if it already existing entity instances corresponding to a relationship, it will auto-fill that relationship from the object cache. It's not issuing a series of circular queries forever.

0
9/6/2019 1:15:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow