MapsterMapper / Mapster

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

Misleading exception message for ctor argument names #719

Open Ekkeir opened 3 months ago

Ekkeir commented 3 months ago

There's an exception produced when mapping to a class with a ctor:

public class Destination
{
    public Destination(int number)
    {
        Id = number;
    }

    public int Id { get; }
}

public class Source
{
    public int Number { get; set; }
}

[Fact]
public void Should_Map()
{
    var config = new TypeAdapterConfig();

    config.ForType<Source, Destination>()
        .Map(dest => dest.Id, source => source.Number);

    config.Compile(); // throws an exception
}

The following exception is produced:

System.InvalidOperationException : No default constructor for type 'Destination', please use 'ConstructUsing' or 'MapWith'.

The exception message seems misleading as (I may have missed it in documentation) mapster seems to depend on argument names. Renaming Destination ctor argument from number to id is enough for the test to succeed. That is, changing to the following:

public class Destination
{
    public Destination(int id)
    {
        Id = id;
    }

    public int Id { get; }
}

Suggestions:

stagep commented 3 months ago

What should happen in this scenario if name-dependency was reduced?

public class Destination
{
    public Destination(int number1, int number2)
    {
        Id1 = number2;
        Id2 = number1;
    }
    public int Id1 { get; }
    public int Id2 { get; }
}