Skip to content

Error mapping with existing object and init properties #536

Closed
@YaroslavMudryk

Description

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?

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions