c# - .Net Core 2.0外键默认为0

标签 c# .net entity-framework models code-first

我有一个使用 .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/

相关文章:

c# - 创建并行任务,如何限制新任务创建?

c# - C# 的 Actors 有什么好的实现吗?

.net - NavigationService 什么时候初始化?

c# - AspNetUsers (Identity) 与自定义数据库中其他表之间的多对多关系

c# - api-independent 顶点处理的好的代码结构是什么?

c# - 无法读取 Windows 8 中的注册表值

c# - 一次移动两个 WPF 窗口?

c# - 带有 null 的字符串如何给出除 null 之外的其他结果

c# - 如何使用用户输入的日期比较可为空类型的日期?

c# - ASP.Net 无法发送电子邮件