Skip to content

Instantly share code, notes, and snippets.

@PhonicUK
Created January 30, 2022 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PhonicUK/81afbba51a2b8ab46a66ac4da3937335 to your computer and use it in GitHub Desktop.
Save PhonicUK/81afbba51a2b8ab46a66ac4da3937335 to your computer and use it in GitHub Desktop.
Date Only Converters for EF.
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace MyProject.Data
{
/// <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))
{ }
}
/// <summary>
/// Converts <see cref="DateOnly?" /> to <see cref="DateTime?"/> and vice versa.
/// </summary>
public class NullableDateOnlyConverter : ValueConverter<DateOnly?, DateTime?>
{
/// <summary>
/// Creates a new instance of this converter.
/// </summary>
public NullableDateOnlyConverter() : base(
d => d == null
? null
: new DateTime?(d.Value.ToDateTime(TimeOnly.MinValue)),
d => d == null
? null
: new DateOnly?(DateOnly.FromDateTime(d.Value)))
{ }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment