Skip to content

CompileException when mapping record with DateTime to class with optional constructor parameter #954

@moikot

Description

@moikot

Mapping from a record containing a DateTime to a class with a constructor that has a default DateTime parameter causes a Mapster.CompileException.

Environment

Mapster version: 10.0.8-pre06
.NET version: net10.0

Repro

public class DateTimeFooDto
{
    public DateTime Timestamp { get; set; }

    public DateTimeFooDto(DateTime timestamp = default(DateTime))
    {
        this.Timestamp = timestamp;
    }
}

record DateTimeFoo(DateTime Timestamp);

public class DateTimeMappingTests
{
    [Fact]
    public void DateTimeMapping()
    {
        // Arrange
        var src = new DateTimeFoo(DateTime.Today);

        // Act
        var foo = src.Adapt<DateTimeFooDto>();

        // Assert
        foo.Timestamp.ShouldBe(src.Timestamp);
    }
}

Actual behavior

Throws:

Mapster.CompileException: Error while compiling
...
System.ArgumentException: Argument types do not match
   at System.Linq.Expressions.Expression.Constant(Object value, Type type)
...

Expected behavior

Mapping should succeed and foo.Timestamp should equal src.Timestamp.

It looks like there are several workarounds, but my problem is that I'm using a code generator and changing it will affect lot's of dependencies. So I have to use MapWith in such cases.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions