Search code examples
.netentity-frameworkasp.net-core.net-5

Create EF Core One-To-Many Relationship data through asp.net core POST


I have this simple model:

public class Form
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public string Name { get; set; }

    public List<FormField> FormFields { get; } = new List<FormField>();
}
public class FormField
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public string Name { get; set; }
    public string Value { get; set; }
}

And a controller method:

public IActionResult Post([FromBody] Form item)
{
    EntityEntry<Form> entityEntry = Context.Add(item);
    ModuleContext.Database.SaveChanges();
    return Ok(entityEntry.Entity);
}

When I now post something like that:

{
  "Name": "Test Name",
  "FormFields": [
    {
      "Name": "Field Name",
      "Value": "Field Value"
    }
  ]
}

Only the Name of the Form is set but no new Form Field is created. Even the "item" returned by FromBody only contains Form.Name but FormFields are empty.

How can I create multiple FormFields through the API?


Solution

  • If I understand correctly Form.FormFields is always empty list no mater what the input is. If that's the case the reason behind it is that FormFields does not have setter and cannot be set. Try adding set; for FormFields (not 100% sure but private set; should be sufficient)