EntityFrameworkCore:如何将具有外键的实体保存到另一个模型?

EntityFrameworkCore: How to save an entity with ForeignKey to another model?

我有一个模型与另一个模型相关:

public class Portfolio : BaseEntity, IEntityBase
    {
        public string Name { get; set; }
        public Org Organization { get; set; }
        public bool IsPrivate { get; set; }
    }

当我尝试保存它时(将 organization 字段的值指向数据库中的现有记录),ModelState 无效("Organization":输入无效) .

我将 Organizationid 与其余有效负载一起发送:

{
    "Name": "Port 1",
    "Organization": 16
}

控制器代码非常简单:

[HttpPost]
public IActionResult Create([FromBody]Portfolio item){
     if (ModelState.IsValid){
         _PortfolioRepo.Add(item);
         _PortfolioRepo.Commit();
         return new OkObjectResult(item);
         }
     else{
        return BadRequest(ModelState);
     }
}

有趣的是,当我在有效负载中指定 Organization 字段时,Create() 方法中的 item 将作为 null 出现,所以我可以' t 手动从其 repo 中检索 Organization 和 link 到 Portfolio。当我省略 Organization 时,它会很好地保存实体。

如果我在有效负载中包含 Organization 的详细信息,则 EF 将在数据库中保存一条 new 组织记录。但是我如何 link 现有模型与保存新模型?

在你的 Portfolio 模型中你有这个 属性:

public Org Organization { get; set; }

请注意 属性 的类型是 Org。因此,由于显而易见的原因,将其设置为数字将不起作用。尝试将您的模型稍微更改为如下所示:

public int OrganizationId { get; set; }

[ForeignKey("OrganizationId")]
public Org Organization { get; set; }

这将告诉 EF Organization 属性 是一个导航 属性,它的外键是 OrganizationId。设置 OrganizationId 属性 它应该可以工作。