简体   繁体   中英

EF Core ModelState.IsValid Always return False , Because navigation property is null

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. 在此处输入图像描述

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM