MapsterMapper / Mapster

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

Error mapping with existing object and init properties #536

Closed YaroslavMudryk closed 1 year ago

YaroslavMudryk commented 1 year ago

I have object User and UserDto:

public class User
{
   public int Id { get; init; }
   public string Name { get; init; }
}

public class UserDto
{
   public int Id { get; init; }
   public string Name { get; init; }
}

Also i have config:

public class UserMappingRegister : IRegister
{
    public void Register(TypeAdapterConfig config)
    {
        config.NewConfig<User, UserDto>()
            .MapToConstructor(true)
            .ConstructUsing(s => new UserDto());
    }
}

And interface for mappers:

[Mapper]
public interface IUserMapper
{
    Expression<Func<User, UserDto>> UserProjection { get; }
    UserDto MapTo(User user);
    UserDto MapTo(User user, UserDto userDto);
}

As result I get the generated file:

public partial class UserMapper: IUserMapper
{
    public Expression<Func<User, UserDto>> UserProjection => p1 => new UserDto()
    {
        Id = p1.Id,
        Name = p1.Name
    }

    public UserDto MapTo(User p2)
    {
        return p2 == null ? null : new UserDto()
        {
            Id = p2.Id,
            Name = p2.Name
        };
    }

    public UserDto MapTo(User p3, UserDto p4)
    {
        if (p3 == null)
        {
            return null;
        }
        UserDto result = p4 ?? new UserDto();

        result.Id = p3.Id; //there is an error due to property marked as init
        result.Name = p3.Name; //there is an error due to property marked as init
        return result;
    }
}

Can someone help me?

andrerav commented 1 year ago

This scenario is not supported by Mapster.Tool at the moment. PR's are welcome.

YaroslavMudryk commented 1 year ago

Ok, thanks a lot!

stormaref commented 1 year ago

I'm working on it