如何在ASP.NET Web API中创建一对多关联对象?

How to create one-to-many related object in ASP.NET Web API?

我有两个实体

public class Tax
{
    public int Id { get; set; }
    public string Name { get; set; }

    public int ClientId { get; set; }
    public Client Client { get; set; }
}
public class Client
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<Tax> Taxes { get; set; }

}

并且在这种方法中,我想使用 ClientId 在 Client 和 Tax 之间创建关系,但是我在客户端收到 The Client field is required 错误,所以我想要忽略字段 Client.

我的问题是如何忽略现场客户端,或者如果我做错了什么,那么如何在 Post 方法中创建一对多关系? (我是 ASP.NET 的新手,很抱歉这是一个愚蠢的问题。)

    [HttpPost]
    public IActionResult Post(Tax tax)
    {
        tax.Client = (from c in context.Clients
                     where c.Id == tax.ClientId
                     select c).FirstOrDefault<Client>();

        context.Taxes.Add(tax);
        context.SaveChanges();
        return Created("api/taxes", tax);
    }

您只需要使 ClientId 可以为空。它的作用与 optioanal 相同。

  public int? ClientId { get; set; }
    public Client Client { get; set; }

或者如果您使用 net 6,您也必须使 Client 也可为空

 public int? ClientId { get; set; }
 public Client? Client { get; set; }

但是您可以从项目中删除可为空的选项,从而永远避免所有这些额外的问题

<PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <!--<Nullable>enable</Nullable>-->
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>

在这种情况下,如果 tax 已经有一个 ClientId,您只需要

context.Taxes.Add(tax);
context.SaveChanges();