這里有 2 個模型
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; }
}
如您所見,公司屬性是 EF Core 的導航屬性。但是當我提交表單以創建產品時,ModelState.IsValid 總是回傳 False。原因是導航屬性“公司”為空。
現在,我可以將導航屬性設定為可空屬性來解決這個問題。
public virtual Company? Company { get; set; }
但是這個問題還有其他解決方案嗎?
謝謝。
uj5u.com熱心網友回復:
您必須使用 net 6 您在所有課程中都會遇到此問題,您必須設法解決它 - 使每個屬性都可以為空,就像您對 Company 所做的那樣,或者從您的專案配置中洗掉可為空的選項(或對其進行評論)
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<!--<Nullable>enable</Nullable>-->
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/446532.html
標籤:C# asp.net-mvc asp.net 核心 实体框架核心 asp.net-core-mvc
上一篇:我無法通過API在博客上保存圖片
