Reputation: 43
There are 2 Models here blow
public class Company
{
[Key]
public int Id { get; set; }
[Required]
[MaxLength(100)]
public string Name { get; set; }
[Required]
[MaxLength(50)]
public string Country { get; set; }
[Required]
[MaxLength(50)]
public string Type { get; set; } = "Client";
public DateTime CreatedDateTime { get; set; } = DateTime.Now;
public List<Product> Products { get; set; }
}
public class Product
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(25)]
public string ProductCode { get; set; }
[Required]
[StringLength(25)]
public string ProductType { get; set; }
[StringLength(25)]
public string MarketArea { get; set; }
[Required]
public int CompanyId { get; set; }
public string? ReferenceCode { get; set; }
public string? SpecialStructure { get; set; }
[StringLength(255)]
public string? Note { get; set; }
[Required]
public DateTime CreateDate { get; set; } = DateTime.Now;
public virtual Company Company { get; set; }
}
As you can see the Company Property is a Navigation Property for EF Core.
but when I submit the form to create the product, the ModelState.IsValid always returns False. and the reason is the navigation property "Company" Is null.
for now, I can set the navigation property as nullable property to solve this problem.
public virtual Company? Company { get; set; }
but is there any other solution for this problem?
thanks.
When I Set project property disable or add #nullable disable at the top of the model file.
the Navigation Property "Company" is not included in the ModelState anymore.
Upvotes: 3
Views: 1460
Reputation: 43939
you must be using net 6 You will have this problem in all your classes and you have to way to fix it - make each property nullable, as you did already with Company , or remove nullable option from you project config ( or comment it )
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<!--<Nullable>enable</Nullable>-->
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
Upvotes: 2