【问题标题】:my api does not return the complete object我的 api 没有返回完整的对象
【发布时间】:2019-05-08 08:12:17
【问题描述】:

我从 .netcore 的 API 开始,我有一个外键,当我进行查询时,值为 null

在那种情况下,我读到 include 是用来获取它的值的,但是当我使用它时,它并没有显示表的所有值,并且在断点中,我看到它具有径向效果并且它不会从那里经过

我的控制器

public class ComidasController : ControllerBase
    {
        private readonly testcoreContext _context;

        public ComidasController(testcoreContext context)
        {
            _context = context;
        }

        // GET: api/Comidas
        [HttpGet]
        public List<Comida> GetComida()
        {
            var prueba =_context.Comida.ToList();
            return prueba;
        }

        // GET: api/Comidas/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Comida>> GetComida(int id)
        {
            var comida = await _context.Comida.FirstOrDefaultAsync(x=> x.Id==id);

            if (comida == null)
            {
                return NotFound();
            }

            return comida;
        }

我的课

{
    public partial class Comida
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int? Type { get; set; }

        public virtual Types TypeNavigation { get; set; }
    }
}
public partial class Types
    {


        public int Id { get; set; }
        public string Name { get; set; }

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

【问题讨论】:

  • 你是否尝试找到? var comida = await _context.Comida.FindAsync(id)
  • 你的完整对象包含循环依赖。使用此类中首选的数据传输对象 (DTO)

标签: c# linq asp.net-core


【解决方案1】:

正如 ilkerkaran 所说,您的 JSON 中存在循环依赖,您可以通过将以下内容添加到您的启动中来告诉您的应用忽略它。

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

【讨论】:

  • 我已经在 servicesConfigure 中复制了该代码,但现在 api 像这样返回我 link
  • @PedroSosa 您的预期结果是什么?
  • @PedroSosa 在我看来还不错,你在期待什么?
  • 那么总是在类型中返回 comida ?,因为我已经看到了它不重复次要对象内的主要对象的示例,我希望它不会这样做
  • @PedroSosa 如果我理解正确,你可以有一个 Id 列表(公共虚拟 ICollection Comidas)而不是对象,否则它们将继续相互引用
【解决方案2】:

您的完整对象包含循环依赖。在这种情况下首选使用数据传输对象 (DTO)。但是,您可以使用匿名类型:

await _context.Comida.Where(x=> x.Id==id)
.Select(comida => new {
    id= comida.Id,
    name= comida,Name,
    type= comida.Type,
    typeNavigation= comida.TypeNavigation })
.FirstOrDefaultAsync();

【讨论】:

    猜你喜欢
    • 2011-09-16
    • 2011-12-09
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多