【问题标题】:EntityFrameworkCore: How to save an entity with ForeignKey to another model?EntityFrameworkCore:如何将具有 ForeignKey 的实体保存到另一个模型?
【发布时间】:2017-11-12 04:36:27
【问题描述】:

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

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

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

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

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

而且Controller代码很简单:

[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 出现,因此我无法从其 repo 中手动检索 Organization并链接到Portfolio。当我省略Organization 时,它会很好地保存实体。

如果我将Organization 的详细信息包含在有效负载中,那么EF 将在数据库中保存一个 组织记录。但是如何链接到现有模型而不是保存新模型?

【问题讨论】:

    标签: c# asp.net-core asp.net-core-mvc entity-framework-core asp.net-core-webapi


    【解决方案1】:

    在您的 Portfolio 模型中,您拥有此属性:

    public Org Organization { get; set; }
    

    请注意属性类型为Org。因此,出于显而易见的原因,将其设置为一个数字将不起作用。试着把你的模型改成这样:

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

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

    【讨论】:

    • 您还应该为 Org 属性添加“虚拟”关键工作,以启用延迟加载并获得更有效的更改跟踪
    • @Hassan Lazy Loading 目前在 EFC 中不存在
    猜你喜欢
    • 1970-01-01
    • 2015-02-27
    • 2020-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-27
    • 1970-01-01
    相关资源
    最近更新 更多