Try this
public class YourDbContext : DbContext
{
Ctors() {...}
protected override void ConfigureConventions(ModelConfigurationBuilder builder)
{
builder.Properties<DateOnly>()
.HasConversion<DateOnlyConverter>()
.HasColumnType("date");
}
}
/// <summary>
/// Converts <see cref="DateOnly" /> to <see cref="DateTime"/> and vice versa.
/// </summary>
public class DateOnlyConverter : ValueConverter<DateOnly, DateTime>
{
/// <summary>
/// Creates a new instance of this converter.
/// </summary>
public DateOnlyConverter() : base(
d => d.ToDateTime(TimeOnly.MinValue),
d => DateOnly.FromDateTime(d))
{ }
}
EDIT: with RC2 this does not work for nullable types.
EDIT 2: with NET6 release version this works for nullable types again, and more than that, you dont need to have a separate converter for “DateOnly?” anymore.
EDIT 3: with NET 8 built-in support has been added and the only thing you need to do is:
public class YourDbContext : DbContext
{
Ctors() {...}
protected override void ConfigureConventions(ModelConfigurationBuilder builder)
{
builder.Properties<DateOnly>()
.HasColumnType("date");
}
}