riok / mapperly

A .NET source generator for generating object mappings. No runtime reflection.
https://mapperly.riok.app
Apache License 2.0
2.95k stars 148 forks source link

Mapping DateTime to a specific TimeZone on the fly #1142

Closed stefanMinch3v closed 8 months ago

stefanMinch3v commented 9 months ago

We have a multitenant app where tenants have different time zones stored in their app settings. For example a CustomerDb object has NextPayingDate which is UTC stored in the database, so whenever we pick the Customer with the NextPayingDate (UTC) from EntityFramework we have to map it to the Settings where the specific time zone is located. Therefore it comes the need if I can do something similar to AutoMapper with IValueConverter on the fly, whenever there is a map between Dates it uses the Tenant specific TimeZone. Is it possible to do the same with Mapperly?

Example

public async Task<CustomerDto> GetCustomerWithTimeZone(Guid customerId) 
{
    var customerSettings = await dbContext.Settings.FirstOrDefaultAsync(x => x.CustomerId == customerId);

    var customerWithTimeZone = await dbContext
        .Customers
        .Where(x => x.Id == customerId)
        .AutoMap<CustomerDto>(customerSettings) // here it maps all DateTime fields to TimeZone specific thanks to IValueConverter on AutoMapper
        .FirstOrDefaultAsync();

    return customerWithTimeZone;
}

public class CustomerDto
{
    public Guid Id { get; set; }
    public DateTime NextPayingDate { get; set; } // with correct TimeZone here set up in AutoMapper
    // other date time properties are also mapped to specific TimeZone
}

public class Customer
{
    public Guid Id { get; set; }
    public DateTime NextPayingDate {get;set;}
}

public class Settings 
{
    public Guid Id { get; set; }
    public Guid CustomerId { get; set; }
    public string TimeZone { get; set; }
}
latonz commented 9 months ago

This sounds like business logic which should actually not happen in an object mapper. You should be able to implement this either by using user-implemented mapping method for the conversion from DateTime to DateTime or before-/after-map.

stefanMinch3v commented 8 months ago

Thank you, will take a look for a custom implementation