关于c#:无法在Entity Framework中包含关系数据

Cannot include relational data with Entity Framework

我正在尝试在我的公司模型中包含关系数据。当我不使用Include时,我得到了答案,但是当我不包括Postman中的Could not get any response时。

1
2
3
4
5
6
7
8
public async Task<IActionResult> Get(string with, string orderBy)
{
   CustContext context = new CustContext();

   var companies = context.Companies.Include(c => c.Stores).ToListAsync();

   return Ok(companies);
}

我想以json格式返回答案,当不包括时由它自行处理。

有人知道什么地方进展不顺利?

编辑

调试时,我看到companiesStores一起设置正确。返回结果时一定有问题。


我找到了解决方案。显然,我们需要明确告知框架不要继续包含(直到无穷远为止)。因此,必须将其添加到startup.cs

1
2
3
4
services.AddMvc().AddJsonOptions(options =>
{
    options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
});