SQL Server added the date (and time) data types in 2008 - now, 15 years later, you can finally take full advantage of these data types with Entity Framework Core and save at least 50% disk space and bandwidth with date.

The DateOnly and TimeOnly types are welcome new additions to .NET that were added in .NET 6 in 2021.

DateOnly can be useful to properly represent for example date of birth or invoice date.

These new types map directly to the existing date and time data types in SQL Server / Azure SQL Database.

Steve Gordon - MVP has a nice blog post about using the types.

Previously, the date and time columns were mapped to .NET DateTime and TimeSpan, but that is not a correct mapping for either, since DateTime also includes time elements, and TimeSpan can exceed 24 hours.

In this blog post I will show how you can make use of these types in EF Core 6 or later, including EF Core 8.

Using DateOnly and TimeOnly with EF Core 6 or 7

To use DateOnly and TimeOnly with EF Core 6 or 7, I have published a NuGet package, that enables you to use these types for queries, migrations and reverse engineering.

dotnet add package ErikEJ.EntityFrameworkCore.SqlServer.DateOnlyTimeOnly

The following table show which version of this library to use with which version of EF Core.

EF Core Version to use
6.0 6.0.x
7.0 7.0.x

To use the package once installed, enable DateOnly and TimeOnly support by calling UseDateOnlyTimeOnly inside UseSqlServer. UseSqlServer is is typically called inside Startup.ConfigureServices or OnConfiguring of your DbContext type.

options.UseSqlServer(
    connectionString,
    x => x.UseDateOnlyTimeOnly());

Add DateOnly and TimeOnly properties to your entity types. Or reverse engineer a table with date and time columns.

class EventSchedule
{
    public int Id { get; set; }
    public DateOnly StartDate { get; set; }
    public TimeOnly TimeOfDay { get; set; }
}

Insert data.

dbContext.Add(new EventSchedule { StartDate = new DateOnly(2022, 12, 24), TimeOfDay = new TimeOnly(12, 00) });
dbContext.SaveChanges();

Query.

var eventsOfTheDay = from e in dbContext.EventSchedules
                     where e.StartDate == new DateOnly(2022, 10, 12)
                     select e;

Using DateOnly and TimeOnly with EF Core 8

EF Core 8 natively supports DateOnly and TimeOnly, so you do not need any additional packages and UseXxx statements to use them.

There is a good docs sample on how to use them.

You just need to be aware of a potential breaking change, that are well described in the docs.

Hope this blog post inspired you to have a look at your database schema, and reconsider if there are more use cases for date and time.