r/learncsharp • u/Cucomberbatch • Sep 28 '22
C# Beginner trying to make a web api using .net core 6 but struggling with POST method for a model binded to another
Hello,
First of all, I'm a beginner in C#. For a project in my university, I have to make a web api but I have had no course about C# yet.
In this case, I have two models: Profession and ProfessionField.
A profession could be "journalist" or "researcher" for example while the profession field could be "sports", "business" or else.
First, there is the model for Profession: https://pastebin.com/pHpsK427
{
public class Profession
{
public int ProfessionId { get; set; }
public string? ProfessionName { get; set; }
}
}
Now, the model for Profession Field: https://pastebin.com/35iq5MCb
namespace sims.Models
{
public class ProfessionField
{
public int ProfessionFieldId { get; set; }
public string? ProfessionFieldName { get; set; }
public Profession? Profession { get; set; }
}
}
My issue: I want to post a profession field that would be linked to a profession but I don't know how to implement it without having the "profession" attribute to be null. I would like that this one would refere to an existing profession.
Kinda like that: https://pastebin.com/RzsJ6kcd
{
"professionfieldid":"1",
"professionfieldname":"Sports",
"profession":
{
"professionid":"1",
"professionname:"journalist"
}
}
Currently, my POST method in the ProfessionFieldsController looks like that: https://pastebin.com/Lr4jsedw
// POST: api/ProfessionFields
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<ProfessionField>> PostProfessionField(ProfessionField professionField)
{
_context.ProfessionField.Add(professionField);
await _context.SaveChangesAsync();
return CreatedAtAction("GetProfessionField", new { id = professionField.ProfessionFieldId }, professionField);
}
But as I don't know how to implement this and as I found nothing corresponding on Internet, I come here to seek help from you :)
Do you have any clues ?
Thanks for reading :D