Search code examples
asp.net-coreef-core-2.2

When including other entities other lists are loaded too which leads into a recursion, how can i prevent this?


I have a big database in the background storing:

public partial class Phone
    {
        public string Imei { get; set; }
        public int ColourId { get; set; }
        public int StorageId { get; set; }
        public int TypeId { get; set; }
        public int ModelId { get; set; }
        public int PurchasePrice { get; set; }
        public DateTime? SaleDate { get; set; }
        public DateTime? RentalStart { get; set; }
        public DateTime? RentalFinish { get; set; }

        public virtual Colour Colour { get; set; }
        public virtual Storage Storage { get; set; }
        public virtual Type Type { get; set; }
    }
public partial class Storage
    {
        public Storage()
        {
            Phone = new HashSet<Phone>();
        }

        public int StorageId { get; set; }
        public string Amount { get; set; }

        public virtual ICollection<Phone> Phone { get; set; }
    }

And I am requesting for the Phone Data like this in my WebAPI:

[HttpGet]
// GET: Phones
public async Task<IActionResult> Index()
{
   var phoneCalculatorContext = _context.Phone.Include(p => 
   p.Colour).Include(p => p.Storage).Include(p => p.Type);
   return Ok(await phoneCalculatorContext.Take(10).ToListAsync());
}

I have posted the JSON Response here:

https://textuploader.com/1dtu2

As you can see in my response is storage included (as expected) but storage has a reference to my Phone Collection and this goes on and on and on (like an recursion)

Is it possible to not get the lists? Because I dont need the lists I just need to get the amount of storage but not the pone list.

Sorry for the poor understanding of EF but I am pretty new to this.


Solution

  • If you don't need that an storage know in how many phones it's, you can remove the ICollection property. other solution is mark the phones property in storage as this

    [JsonIgnore]
    public virtual ICollection<Phone> Phone { get; set; }