ModelState with entities relationship

51 Views Asked by At

I am trying to make an a form for booking with client-side validation and backside validation. The client-side validation is successful and works properly. But there's a problem in server-side validation. This is from the Booking entity which has a one-to-one relationship with a customer:

//Relationship

[ForeignKey("Customer")]
public int customerID { get; set; }

public Customer Customer { get; set; }

I send the customerID from the booking form

<input asp-for="Booking.customerID" value="1" hidden/>

but when I submit the form, the modelState will be false, and when I look for the reason, it become for the relationship

{[Booking.Customer, SubKey={Customer}, Key=Booking.Customer, ValidationState=Invalid]}

I am working with n-tier architecture in ASP.NET, and I have generic repository and interface.

What is the problem?

1

There are 1 best solutions below

3
Qing Guo On

If the app was built with <Nullable>enable</Nullable>, a missing value for Customer property in a JSON or form post results in a validation error.

To avoid the modelState will be false, use of the ? suffix to declare a nullable reference type to allow null or missing values to be specified for the Customer property. Try to add ? like:

public Customer? Customer { get; set; }