RepoDB icon indicating copy to clipboard operation
RepoDB copied to clipboard

Bug: PropertyHandlerMapper for DateTime and DateTime?

Open Kaizer69 opened this issue 3 years ago • 1 comments

Bug Description

You cannot use a PropertyHandler (the attribute works correctly) with either values or Nullable values.

// Tried all possible combinations of .Add<>
PropertyHandlerMapper.Add<DateTime, DateTimeHandlers>(new DateTimeHandlers(), true);
PropertyHandlerMapper.Add<DateTime?, DateTimeNullableHandlers>(new DateTimeNullableHandlers(), true);

// Also used FluentMapper:
FluentMapper.Type<DateTime?>().PropertyHandler<DateTimeNullableHandlers>(new DateTimeNullableHandlers(), true);

Exception Message:

If you register DateTimeHandlers (with nullable generic)

No coercion operator is defined between types 'System.DateTime' and 'System.Int64'.

or if you register only the DateTimeHandlers (without nullable generic DateTime)

System.InvalidOperationException: Nullable object must have a value.

Schema and Model:

[Table("Articles")]
public record EArticle {
[Primary]
public int    ID         { get; set; }
public string Section    { get; set; }
public string ArticleID  { get; set; }
public string Title      { get; set; }
public DateTime Date_Added { get; set; }
public DateTime? Date_Fetched { get; set; }
}

// Handlers (for DateTime)
public class DateTimeHandlers : IPropertyHandler<long, DateTime> {
public DateTime Get(long value, ClassProperty property) {
	return DateTimeOffset.FromUnixTimeMilliseconds(value).DateTime;
}

public long Set(DateTime value, ClassProperty property) {
	return new DateTimeOffset(value).ToUnixTimeMilliseconds();
}
}
	
	
// Handlers (for DateTime?)	
public class DateTimeNullableHandlers : IPropertyHandler<long?, DateTime?> {	
public DateTime? Get(long? value, ClassProperty property) {
	return (value.HasValue) ? DateTimeOffset.FromUnixTimeMilliseconds(value.Value).DateTime : null;
}

public long? Set(DateTime? value, ClassProperty property) {
	return (value != null) ? new DateTimeOffset(value.Value).ToUnixTimeMilliseconds() : null;
}
}

Library Version:

Example: RepoDb v1.12.7 and RepoDb.SqlLite

PS: Instead using the PropertyHandlerAttribute, just works perfectly.

[Table("Articles")]
public record EArticle {
[Primary]
public int    ID         { get; set; }
public string Section    { get; set; }
public string ArticleID  { get; set; }
public string Title      { get; set; }

[PropertyHandler(typeof(DateTimeHandlers))]
public DateTime Date_Added { get; set; }

[PropertyHandler(typeof(DateTimeNullableHandlers))]
public DateTime? Date_Fetched { get; set; }
}

Kaizer69 avatar Mar 26 '21 21:03 Kaizer69

Hey, thank you for this report and we will get back to you soon.

mikependon avatar Mar 26 '21 21:03 mikependon