Skip to content

Automapper version 11.0.0 breaks mapping to records in some cases #3834

@grisharav

Description

@grisharav

Source/destination types

class Original
{
    public float? PropertyTimeSec { get; set; }
    public int? PropertyNum { get; set; }
}

record Target(TimeSpan? PropertyTime = null, int? PropertyNum = null);

Mapping configuration

class MyProfile : Profile
{
    public MyProfile()
    {
        CreateMap<float, TimeSpan>()
            .ConstructUsing(f => TimeSpan.FromSeconds(f))
            .ReverseMap()
            .ConstructUsing(t => (float)t.TotalSeconds);


        CreateMap<Target, Original>()
            .ForMember(dst => dst.PropertyTimeSec, opt => opt.MapFrom(s => s.PropertyTime))
            .ReverseMap();
    }
}

Version: 11.0.0

Expected behavior

Both properties of the record are updated

Actual behavior

The TimeSpan property of the record is not set and remains null.

Steps to reproduce

Here's a full snippet. This works as expected in 10.1.1 and fails in 11.0.0
If we turn the Target to a class, all works as expected

using AutoMapper;

var config = new MapperConfiguration(c => c.AddProfile(new MyProfile()));
var mapper = new Mapper(config);
var o = new Original
{
    PropertyNum = 78,
    PropertyTimeSec = 56
};

var t = mapper.Map<Target>(o);
Console.WriteLine(t); //Should have 56 seconds in PropertyTime

class Original
{
    public float? PropertyTimeSec { get; set; }
    public int? PropertyNum { get; set; }
}

record Target(TimeSpan? PropertyTime = null, int? PropertyNum = null);

class MyProfile : Profile
{
    public MyProfile()
    {
        CreateMap<float, TimeSpan>()
            .ConstructUsing(f => TimeSpan.FromSeconds(f))
            .ReverseMap()
            .ConstructUsing(t => (float)t.TotalSeconds);


        CreateMap<Target, Original>()
            .ForMember(dst => dst.PropertyTimeSec, opt => opt.MapFrom(s => s.PropertyTime))
            .ReverseMap();
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions