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

Time:10-21

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?

CodePudding user response:

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)

CodePudding user response:

Ok - for understaning there is relation:

One Form have multiple FormFields


There is properly configured relationships?

modelBuilder.Entity< Form >()
    .HasMany(c => c.FormFields)
    .WithOne(e => e.Form);

If this json don't add the element to database properly:

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

then there is an option for add the FormFields and Name seperately:

EntityEntry<Form> entityEntry = Context.Add(item);

foreach(field in item.FormFields){
   EntityEntry<FormFields> entityEntry = Context.Add(field);
}

ModuleContext.Database.SaveChanges();
return Ok(entityEntry.Entity);

Also reference for many to many:

How to insert a model in ef 6 with a many to many relationship

  • Related