POST method with List 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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x