riok / mapperly

A .NET source generator for generating object mappings. No runtime reflection.

Home Page:https://mapperly.riok.app

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Selecting user implemented mapping method

phil000 opened this issue · comments

Is your feature request related to a problem? Please describe.
Yes.
We have situations where we want to map a DateTime into milliseconds (long), and other times we turn it into seconds (long).
e.g.

   private static long DateTimeToUnixTimeSeconds(DateTime source)
   {
      return source.ToUnixTimeSeconds();
   }

   private static long DateTimeToUnixTimeMilliseconds(DateTime source)
   {
      return source.ToUnixTimeMilliseconds();
   }

Describe the solution you'd like
When we create user implemented mapping methods be useful to be able to specify which one to use (if it is ambiguous). Both the above mapping methods have the same signature.

Could the [MapProperty] attribute include a property that contains the name of the custom mapping\conversion method.

Relevant new / adjusted API surface:

[MapProperty(nameof(DeliveryRate.EndDateTimeUtc), nameof(DeliveryRateResponse.EndDateTimeUnixOffsetMilliseconds), Conversion = nameof(DateTimeToUnixTimeMilliseconds))]

// Expected generated code

target.EndDateTimeUnixOffsetMilliseconds = DateTimeToUnixTimeMilliseconds(source.EndDateTimeUtc);
//or
target.EndDateTimeUnixOffsetMilliseconds = DateTimeToUnixTimeSeconds(source.EndDateTimeUtc);

(Depending on the custom mapping method selected)

Describe alternatives you've considered
We just currently ignore the property using [MapperIgnoreTarget] and map it manually in an 'after map' type situation.

Additional context
no

This would potentially solve one of our other issues.

Specifying the "Kind" of DateTime mappings.

We have DateTime values coming from a database query with a DateTime.Kind of 'Unspecified'. When we map these into our service contract they must be mapped with DateTime.Kind of "Utc" to be serialized correctly.

In auto mapper we currently use:

.ForMember(dest => dest.StartDateTimeUtc, opt => opt.MapFrom(src => DateTime.SpecifyKind(src.StartDateTimeUtc, DateTimeKind.Utc)))

Be useful if we could specify a custom conversion by name for that member. It is DateTime -> DateTime but so are other things. We need a way to disambiguate beyond source -> destination types.

[MapProperty(nameof(DeliveryRate.StartDateTimeUtc), nameof(DeliveryRateResponse.StartDateTimeUtc), Conversion = nameof(DateTimeToDateTimeUtc))]
commented

This seems to be a duplicate of #783 which has landed on main but is not yet released. A next release including this feature should be available in the upcoming days.