1

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

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.