Net Core - .Include() results in loop causing Visual Studio debug to crash

asp.net-core-mvc dbcontext eager-loading entity-framework-core visual-studio-2017

Question

My database has a one-to-many relation between "UsageRecord" and "Dimension"

Database diagram

This is modelled as follows (using a Database-First approach):

public partial class Dimension
    {               
        ...          
        public virtual ICollection<UsageRecord> UsageRecord { get; set; }       
    }

Usage Record class:

      public partial class UsageRecord
        {
            public long Id { get; set; }
            ...
            public long DimensionId { get; set; }    
            public virtual Dimension Dimension { get; set; }              
        }

So, if i query the list of UsageRecords (EagerLoading):

_context.Set<UsageRecord>.Where(x => x.ProductId == productId).ToList()

i get a list of UsageRecord objects I can navigate through during debug: usage record

Please notice that the Dimension object is null, and this is correct since i haven't included it in the query.

Now, If i try to include it, the application crashes:

_context.Set<UsageRecord>.Where(x => x.ProductId == productId).Include(p => p.Dimension).ToList();

crash

Postman exits with a 502 error, and the VS Debug first shows a list of question marks "?" before crashing.

I think this is due to the fact that by Including the Dimension object, this loops through the list of UsageRecords attached and then the Dimension again and again.

How can I avoid it?

Popular Answer

In order to retrieve your result from LINQ query you can solve your issue in these ways:

  • Configure your serializer to ignore loops
  • Create a view model for your controller's action
  • Use anonymous type from Select result in your controller's action


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