Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Error mapping with existing object and init properties #536

Closed
YaroslavMudryk opened this issue Feb 7, 2023 · 3 comments · Fixed by #545
Closed

Error mapping with existing object and init properties #536

YaroslavMudryk opened this issue Feb 7, 2023 · 3 comments · Fixed by #545

Comments

@YaroslavMudryk
Copy link

YaroslavMudryk commented Feb 7, 2023

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?

@YaroslavMudryk YaroslavMudryk changed the title Mapping with existing object and init properties are failed Error mapping with existing object and init properties Feb 7, 2023
@andrerav
Copy link
Contributor

andrerav commented Feb 7, 2023

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

@YaroslavMudryk
Copy link
Author

Ok, thanks a lot!

@stormaref
Copy link
Contributor

I'm working on it

andrerav added a commit that referenced this issue Feb 21, 2023
Fix Issues #536 -> Set properties with reflection if destination has init only properties.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
3 participants