A lightweight, extensible, open-source, and cross-platform version of the Entity Framework data access technology.
Make Birth nullable in both the EF Core entity and the view model, then use null-conditional formatting in the view so a missing birth date renders as an empty string.
Entity and view model
A nullable SQL datetime column should map to DateTime?; EF Core treats nullable value types as optional properties and non-nullable value types as required properties.^1^
// EF Core entity mapped to mytable
public class MyTable
{
public DateTime? Birth { get; set; }
}
// Model passed to the view
public class MyModel
{
public DateTime? Birth { get; set; }
}
Ensure the mapped entity property is nullable—not only the projected view-model property. Otherwise, EF Core can fail while materializing the database row, before assigning the result to MyModel.^2^
The projection then remains straightforward:
var query =
from aa in mydb.MyTable
select new MyModel
{
Birth = aa.Birth
};
Format it safely in the view
Use ?. to call ToShortDateString() only when Birth has a value, and ?? to specify what should be displayed when it is null:^3^
var dob = Model.Birth?.ToShortDateString() ?? "";
Or directly in a Razor view:
<span>@(Model.Birth?.ToShortDateString() ?? "")</span>
To display a label instead of an empty value:
<span>@(Model.Birth?.ToShortDateString() ?? "Not provided")</span>
An equivalent explicit check is:
var dob = Model.Birth.HasValue
? Model.Birth.Value.ToShortDateString()
: "";
Do not use Birth.Value.ToShortDateString() without first checking HasValue; accessing Value when the nullable date is empty throws InvalidOperationException with “Nullable object must have a value.”^4^
If a missing birth date is valid business data, preserving it as null is preferable to replacing it with an arbitrary date such as DateTime.MinValue.
References