Home > Enterprise >  Can I use [Required] and nullable at the same time in Entity Framework Core?
Can I use [Required] and nullable at the same time in Entity Framework Core?

Time:03-17

I'm developing a web application and database using Blazor server-side and Entity Framework Core 6 (with migrations). Currently I'm implementing the model entities and service classes for CRUD operations.

This is an example of a entity-class of an agreement:

public class AgreementElement
{
    [Key]
    public int AgreementElementSeq { get; set; }

    [Required]
    public string Name { get; set; }    

    [Required]
    [Column(TypeName = "decimal(19,2)")]
    public decimal? Price { get; set; }
    
    [Required]
    public DateTime? DateFrom { get; set; }
    
    [Required]
    public DateTime? DateTo { get; set; }

    public bool? IsActive { get; set; }

    ...
}

Nullable types are enabled!

Is the way I'm using [Required] in addition to nullable types common in EF Core/C#?

The reasons for using this are:

  • The field which are nullable (bool? IsActive) is assigned default value true when added into the database, thus it should be possible to contain a null value so it doesn't throw an exception when not set when creating AgreementE-object.
  • The field with [Required] attribute (string Name) is NOT nullable in the database. The default value is "" (which I actually don't want to be possible), so maybe it should be nullable as well?
  • The fields which are both [Required] and nullable:
    1. [Required] makes is NOT nullable in database - nice!
    2. If DateTime field is not nullable (missing ? after DateTime), it will be set to the default value (DateTime.Min) "01/01/0001" or something like that. That leads to extra if (DateFrom == DateTime.Min) {} inside the CRUDs. Not nice!

When using DateTime?, EF Core auto-checks for null and throws exception. Nice! But I need both [Required] and ? after type.

What is the correct way to do this stuff?

Thanks for replies!

CodePudding user response:

Ytou can do something like

[Required]  
public DateTime? DateFrom { get; set; } = null!;

If you are trying to set null on a Required field.

CodePudding user response:

In my side, I try to apply the same logic between persistence data (DB saving in our case) and code. If a property is nullable in DB, I try to set it nullable in C# too.

The other principle I try to follow is business logic first. "Does it make sense that this field is nullable?"

I'd be glad to see other members opinions :)

  • Related