Does the Required attribute have any effect on a navigation property?

c# data-annotations entity-framework entity-framework-6

Question

I have the following code in an EF data model:

[Required]
public IdentityTypeDocument IdentityType { get; set; }

[Required]
[ForeignKey(nameof(IdentityType))]
public int? IdentityTypeId { get; set; }

Does the first Required - on the IdentityTypeDocument property mean anything at all versus the second one - the int property?

1
1
6/13/2017 5:33:53 AM

Accepted Answer

Additionally to the comment conversation and to give this question an answer:

[Required] means the object has to be not null, so on a not nullable type this annotation makes no difference. For nullable types, it makes no difference if the navigation property or the FK property are annotated this way - if the FK is not null, the navigation property has to be an object with this id or you'll receive an error when trying to save to the database; if the navigation property is not null, ChangeTracking will set the FK to be identical to its PK value.

This means both data annotations mean exactly the same, as they pretty much imply each other - this is assuming the one property is configured correctly to be the FK/navigation property corresponding to the other, and neither of the two properties (or the related type, since then no object of this type will be saved to the database anyways) is excluded from the model explicitly.

3
6/13/2017 5:55:22 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow