Home > Net >  Define a column as nullable in model class (ASP.NET)
Define a column as nullable in model class (ASP.NET)

Time:08-21

I need to define a column in a model class as nullable. In .NET Core, addign a ? to the datatype declaration would have done so. But what can I do in this situation?

The model I created is

public class Company
{
    [Key]
    public int ID { get; set; }
    [Required]
    public string CompanyName { get; set; }
    [Required]
    public string Address { get; set; }
    [Required]
    public string CompanyEmail { get; set; }
    [Required]
    public string ClientName { get; set; }
    public string ClientEmail { get; set; } = string.Empty;
    [Required]
    public string PrimaryContact { get; set; }
    public string SecondaryContact { get; set; } = string.Empty;
    [Required]
    public string Software { get; set; }
    public DateTime ContractDate { get; set; }
    public DateTime AMCDate { get; set; }
    public decimal ContractAmount { get; set; }
    public string AnydeskID { get; set; } = string.Empty;
    public string Password { get; set; } = string.Empty;
}

string.Empty seems to be working for string Datatype but what can I do for DateTime and decimal?

Furthermore, DataTime accepts both date and time, is there any way to get only date as its value?

CodePudding user response:

DateTime and decimal are nonnullable Datatypes. That means they have the default value and for use as nullable you must use '?'.

To get only the date or time you can you these codes

 var MyDate = DateTime.Now;
 var MyDay = MyDate.Date;
 var MyTime = MyDate.TimeOfDay;

CodePudding user response:

You can use default to set a default value. (For DateTime it would be January 1, 0001 00:00:00)

public DateTime DateTime {get; set;} =default;

Since DateTime is a none nullable type, DateTime will contain the DateTime default value. If DateTime needs to be nullable, you can do the following:

public DateTime? DateTime {get; set;} =default;

Now DateTime will be null since null is the default Value for a nullable Type.

If you are using a code first database design, then the column will also automatically be set to be able to conatin null values if you use the ? on a Property (this is true for normally nullable types such as string)

  • Related