如何处理与相关实体的entites添加

时间:2017-02-21 08:08:22

标签: entity-framework frontend .net-core

我有2个模特

  public class Licence
  {
    public int Id { get; set; }

    public int CustomerId { get; set; }

    public Customer Customer { get; set; }
   }

  public class Customer
  {
    public int Id { get; set; }

    public int LicenceId { get; set; }

    public virtual Licence Licence { get; set; }
  }

我想与现有客户一起创建许可证

[HttpPut]
public IActionResult CreateLicence([FromBody]Licence licence)
{
  Context.Add(licence);
  Context.SaveChanges();

  return Ok(licence);
}

我现在有几个选择:

1.我可以使用

初始化前端的LicenceId
Licence.CustomerId = (Selected Customer.CustomerId)

2.我可以使用

初始化前端的许可证
Licence.Customer = (Selected Customer Object)

当我做2时,我需要一个extesion方法,我写这个方法来忽略那些难以存在的导航属性。 我个人喜欢2,因为它的代码较小,并且由他自己创建这些导航属性。

  

public int CustomerId {get;组; }

有人能说我这样做的正确方法是什么? 1.还是2?

1 个答案:

答案 0 :(得分:0)

这是我从你的问题中得到的:你想要保存许可证对象,但是添加" CustomerID"在其中,因为许可证表将CustomerID作为外键。

如果我理解你的话:你应该采用方法1.当你阅读数据时,导航属性是有用的。或者,如果您要创建子数据,则需要填充相关的导航属性。