What advantage from Required attribute for nullable field in entity?

1.9k Views Asked by At

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;}
}
2

There are 2 best solutions below

0
On BEST ANSWER

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.

1
On

It has nothing to do with the .NET data type in the first place. Rather, it is the client side counterpart of a database column being nullable or not. If you don't provide a value to a property marked with the Required attribute, then the entity is invalidated without making a database server roundtrip.

Strictly spoken, nullable .NET data types don't make sense for not nullable database columns. But that's not really the point...