Adilet Usonov
Adilet Usonov

Reputation: 136

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

I have two entities

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

}

and in this method, I want to create a relationship between Client and Tax using ClientId, but i am getting The Client field is required error on client side, so I want to ignore field Client.

My question is how to ignore fielf client or if I'm doing something wrong, then how to create one-to-many relationship in Post method? (I'm new to ASP.NET so sorry if this is a stupid question.)

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

Upvotes: 1

Views: 263

Answers (1)

Serge
Serge

Reputation: 43969

you just need to make ClientId nullable. It will do the same as an optioanal.

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

or if you use net 6 you will have to make Client nullable too

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

but you can remove nullable option from project to avoid all this extra problems forever

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

in this case, if tax has a ClientId already, you only need

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

Upvotes: 1

Related Questions