【问题标题】:Create EF Core One-To-Many Relationship data through asp.net core POST通过 asp.net core POST 创建 EF Core 一对多关系数据
【发布时间】:2021-10-20 10:55:11
【问题描述】:

我有这个简单的模型:

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

还有一个控制器方法:

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

当我现在发布类似的内容时:

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

只设置了表单的Name,但没有创建新的表单域。即使FromBody返回的“项目”也只包含Form.Name,但FormFields是空的。

如何通过 API 创建多个 FormField?

【问题讨论】:

    标签: .net entity-framework asp.net-core .net-5 asp.net5


    【解决方案1】:

    如果我理解正确,Form.FormFields 始终是空列表,无论输入是什么。如果是这种情况,其背后的原因是FormFields 没有设置器并且无法设置。尝试为FormFields 添加set;(不是100% 肯定,但private set; 应该足够了)

    【讨论】:

    • 是的,原因可能是缺少二传手。
    【解决方案2】:

    好的 - 了解存在关系:

    一个表单有多个表单域


    是否存在正确配置的关系?

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

    如果这个 json 没有正确地将元素添加到数据库中:

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

    然后有一个选项可以分别添加 FormFields 和 Name:

    EntityEntry<Form> entityEntry = Context.Add(item);
    
    foreach(field in item.FormFields){
       EntityEntry<FormFields> entityEntry = Context.Add(field);
    }
    
    ModuleContext.Database.SaveChanges();
    return Ok(entityEntry.Entity);
    

    也是多对多的参考:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-26
      • 2021-10-11
      • 1970-01-01
      • 2018-06-02
      • 1970-01-01
      相关资源
      最近更新 更多