MapsterMapper / Mapster

A fast, fun and stimulating object to object Mapper
MIT License
4.31k stars 328 forks source link

Func<> property not being set in auto-generated mapper #503

Closed mickvikt closed 1 year ago

mickvikt commented 1 year ago

Hello, I have a question regarding the automatically generated mapper. This is my config:

public class MyRegister : IRegister
{
    public void Register(TypeAdapterConfig config)
    {
        config.NewConfig<FilterParameters, InstanceFilter>()
            .Map(dest => dest.DepartureDateFrom, src => ParseDateFrom(src.DepartureDate));
    }

    private static DateTimeOffset? ParseDateFrom(string date) => ParseDate(date, dates => dates.First());

    private static DateTimeOffset? ParseDateTo(string date) => ParseDate(date, dates => dates.Last());

    private static DateTimeOffset? ParseDate(string date, Func<IEnumerable<string>, string> func)
    {
        var dateToParse = date;
        if (string.IsNullOrEmpty(date))
        {
            return null;
        }

        if (date.Contains('/'))
        {
            dateToParse = func(date.Split('/'));
        }

        return DateTimeOffset.TryParse(dateToParse, out var parseDate) ? parseDate : null;
    }    
}

The problem is that Mapster.Tool generates this mapper class and introduces a private Func<...> property, but it is not being set

    public partial class FilterParametersMapper : IFilterParametersMapper
    {
        private Func<string, DateTimeOffset?> ParseDateFrom1;

        public InstanceFilter Map(FilterParameters p1)
        {
            return p1 == null ? null : new InstanceFilter() {DepartureDateFrom = ParseDateFrom1.Invoke(p1.DepartureDate)};
        }
    }

My question would be: should my mapping logic be declared in some other way for Mapster.Tool to generate a mapper correctly? Thank you.

andrerav commented 1 year ago

Hi @mickvikt, could you try using MapWith() instead? I think that should be a better fit for your use case. Info here: https://github.com/MapsterMapper/Mapster/wiki/Custom-conversion-logic

I'm closing this for now, but let me know if you encounter any other problems that might indicate a bug.