When I use DateTime?
, I can get null value, but in DateTime
datatype getting exception like "Data is null". So, how to get a datetime minvalue instead of null for DateTime
in EF?
CodePudding user response:
Assuming that you have a datetime property as below;
public DateTime? DateProperty { get; set; }
And you can check if it has a value, if not assign min value;
YourModel.DateProperty.HasValue? YourModel.DateProperty.Value : DateTime.MinValue
CodePudding user response:
Represents the smallest possible value of DateTime. This field is read-only.
public static readonly DateTime MinValue;
The following example instantiates a DateTime object by passing its constructor an Int64 value that represents a number of ticks. Before invoking the constructor, the example ensures that this value is greater than or equal to DateTime.MinValue.Ticks and less than or equal to DateTime.MaxValue.Ticks. If not, it throws an ArgumentOutOfRangeException.
// Attempt to assign an out-of-range value to a DateTime constructor.
long numberOfTicks = Int64.MaxValue;
DateTime validDate;
// Validate the value.
if (numberOfTicks >= DateTime.MinValue.Ticks &&
numberOfTicks <= DateTime.MaxValue.Ticks)
validDate = new DateTime(numberOfTicks);
else if (numberOfTicks < DateTime.MinValue.Ticks)
Console.WriteLine("{0:N0} is less than {1:N0} ticks.",
numberOfTicks,
DateTime.MinValue.Ticks);
else
Console.WriteLine("{0:N0} is greater than {1:N0} ticks.",
numberOfTicks,
DateTime.MaxValue.Ticks);
// The example displays the following output:
// 9,223,372,036,854,775,807 is greater than 3,155,378,975,999,999,999 ticks.
link of the article DateTime.MinValue Field