简体   繁体   中英

POST method with List<T> object with EF Core 5.0 API

So I'm new to coding in general and starting to work with .net core 5.0. I'm trying to develop a simple API with Entity Framework Core and I'm having problems when I try to use the POST method. I have a class called Question and another one called Template, which goes as follows

public class Question
{
    public int Id { get; set; }
    public string Answer { get; set; }
    public int Weight { get; set; }
}

public class Template
{
    public int Id { get; set; }
    public List<Question> Questions { get; set; }
}

When I go to Postman with my API running, I enter the following into the POST method:

{
    "questions" : [
    {   "answer" : "a", "weight" : 2  },
    {   "answer" : "b", "weight" : 2  },
    {   "answer" : "c", "weight" : 2  },
    {   "answer" : "d", "weight" : 2  },
    {   "answer" : "a", "weight" : 1  },
    {   "answer" : "b", "weight" : 1  }
    ]
}

But what I get as a response when I call the GET method is something of the sort

[
   {
      "id": 1,
      "questions": null
   },
   {
      "id": 2,
      "questions": null
   }
]

This is the code part with POST and GET in my TemplatesController class

[Route("api/[controller]")]
[ApiController]
public class TemplatesController : ControllerBase
{
    private readonly AlfContext _context;

    public TemplatesController(AlfContext context)
    {
        _context = context;
    }

    // GET: api/Templates
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Template>>> GetTemplates()
    {
        return await _context.Templates.ToListAsync();
    }

    // GET: api/Templates/5
    [HttpGet("{id}")]
    public async Task<ActionResult<Template>> GetTemplate(int id)
    {
        var template = await _context.Templates.FindAsync(id);

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

        return template;
    }

    // POST: api/Templates
    [HttpPost]
    public async Task<ActionResult<Template>> PostTemplate(Template template)
    {
        _context.Templates.Add(template);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetTemplate), new { id = template.Id }, template);
    }

    private bool TemplateExists(int id)
    {
        return _context.Templates.Any(e => e.Id == id);
    }
}

And here is my DbContext class

public class AlfContext : DbContext
{
    public DbSet<Template> Templates { get; set; }

    public AlfContext(DbContextOptions<AlfContext> options)
        : base(options)
    {
    }
} 

Why do I keep receiving "null" as a response in my "questions" field? Am I missing something, or maybe a concept?

Based on your question there, with my experience, I would like you to make sure:

  1. On post, is data saving correctly into question entity.

  2. If so, on get mapping, make sure that your child entities are loaded using eager loading. (like efcore.include() to load the child entities)

If not using any external mappers, Note: Make sure to add a constructor initializing your list.

public class Template
{
    public int Id { get; set; }
    public List<Question> Questions { get; set; }
    public Template()
    {
       Questions = new List<Questions>()
    }
}

Kindly please do have a try with this and let me know if you need additional information from my end.

You are not asking for the related Question entities in your query.

Modify your GET method to -

[HttpGet]
public async Task<ActionResult<IEnumerable<Template>>> GetTemplates()
{
    return await _context.Templates.Include(p=> p.Questions).ToListAsync();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM