Created
January 30, 2022 12:41
-
-
Save PhonicUK/81afbba51a2b8ab46a66ac4da3937335 to your computer and use it in GitHub Desktop.
Date Only Converters for EF.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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