当包含其他实体时,也会加载其他列表,这会导致递归,我该如何防止这种情况发生?

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

我有一个大数据库在后台存储:

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; }
    }

我在我的 WebAPI 中请求 Phone 数据:

[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());
}

我已经在此处发布了 JSON 回复:

https://textuploader.com/1dtu2

正如您在我的回复中看到的那样,存储包括在内(正如预期的那样),但存储引用了我的 Phone Collection 并且这种情况不断发生(就像递归一样)

有没有可能收不到名单? 因为我不需要列表,所以我只需要获取 存储量 数量 不是 列表.

抱歉,我对 EF 的理解很差,但我对此很陌生。

如果您不需要存储知道它在多少部手机中,您可以删除 ICollection 属性。 其他解决方案是将存储中的电话 属性 标记为

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

要禁用自引用序列化,您可以尝试 SerializerSettings.ReferenceLoopHandling 就像

services.AddMvc()
        .AddJsonOptions(opt => {
            opt.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
        }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2);