我有一个使用 .Net Core 2.0 在 Visual Studio 2017 中开发的项目的相当基本的模型。型号匹配以下内容
public class QuoteModel : BaseModel{
public QuoteModel()
{
GetQuoteItems = new List<QuoteItemModel>();
}
[Required]
public int QuoteTypeID { get;set; }
[Required]
[ForeignKey("QuoteTypeID")]
public QuoteTypeModel QuoteType { get;set;}
public ICollection<QuoteItemModel> GetQuoteItems { get; set; }
}
我尝试过使用和不使用 [Required] 注释,但仍然遇到此问题。问题是,如果我创建新的报价,QuoteTypeID 默认为 0,因此如果用户不选择类型,模型仍然有效。我更希望模型通过不将外键默认为某个值来使其自身无效,但是我无法弄清楚为什么外键根本默认为一个值,因为我的大部分研究表明它通常默认为 null ,要求需提供身份证件。
如何使外键“QuoteTypeID”没有默认值但需要设置一个值?
此外,为了清楚起见,BaseModel 仅提供了我在大多数模型中所需的一些标准字段,例如“CreatedOn”和“CreatedBy”。
最佳答案
[ForeignKey("QuoteTypeID")]
应放置在外键本身之上,并且应在引号中包含模型名称,即
[ForeignKey("QuoteType")]
[Required]
public int QuoteTypeID { get;set; }
关于c# - .Net Core 2.0外键默认为0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46791932/