Search code examples
c#asp.net-mvcattributesrequired

What advantage from Required attribute for nullable field in entity?


For example I have an entity Entity and it has a field SomeValue of type double?.

And I set Required attribute for this field. Does this field behaves like double?

public class Entity
{
   [Required]
   public double? SomeValue { get;set;}
}

Solution

  • Here's a practical example, imagine you have an asp.net core controller that takes this request:

    public class ExampleRequest
    {
        [Required]
        public Guid Id { get; set; }
    }
    

    If you execute this request with an empty payload, the validation will succeed. But how? If you omitted Id from the request, and it is required, it should fail...

    In reality, Id defaults to Guid.Empty, so [Required] sees a valid Guid and it passes validation.

    How can we guarantee that an empty payload fails validation? With a nullable required field:

    public class ExampleRequest
    {
        [Required]
        public Guid? Id { get; set; } = default!;
    }
    

    This way, an empty payload will result in a null Id that fails validation.