Reputation: 186
I have a fairly basic model for a project developed in Visual Studio 2017 using .Net Core 2.0. Model matches to the following
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; }
}
I've tried both with and without the [Required] annotation and still run into this issue. The issue is that if I create a new Quote, the QuoteTypeID defaults to 0 so if the user doesn't select a type, the model still remains valid. I'd prefer if the model invalidated itself by not defaulting the foreign key to a value, however I cannot figure out why foreign keys are defaulting to a value at all as much of my research has shown that it normally defaults to null requiring that an ID be provided.
How can I get the foreign key 'QuoteTypeID' to not have a default value but require a value be set?
Also, for the sake of clarity, BaseModel simply provides a few standard fields I wanted in a majority of my models like 'CreatedOn' and 'CreatedBy'.
Upvotes: 2
Views: 776
Reputation: 1093
[ForeignKey("QuoteTypeID")]
Should be placed above the foreign key itself and should have the model name in the quotes i.e.,
[ForeignKey("QuoteType")]
[Required]
public int QuoteTypeID { get;set; }
Upvotes: 2