Skip to content

Mapster.Tool - Error generating two-way mappings with init properties. #422

Description

@DonnelCyril

Best to explain the issue with an eg:

Below is my domain model

public class SalesOrder
{
    public Guid Id { get; init; }
    public decimal Total { get; init; }
    public string Status { get; init; }
}

and I am trying to create a corresponding Dto using the Mapster.Tool

    <Target Name="Mapster">
        <Exec WorkingDirectory="$(ProjectDir)" Command="dotnet mapster model -a &quot;$(TargetDir)$(ProjectName).dll&quot; -n &quot;Mapster.TestBench.Dtos&quot; -o &quot;Dtos/Generated&quot;" />
        <Exec WorkingDirectory="$(ProjectDir)" Command="dotnet mapster extension -a &quot;$(TargetDir)$(ProjectName).dll&quot; -n &quot;Mapster.TestBench.DtoMapper&quot; -o &quot;Dtos/Generated&quot;" />
    </Target>

The Dto object gets generated as expected.

    public partial class SalesOrderDto
    {
        public Guid Id { get; set; }
        public decimal Total { get; set; }
        public string Status { get; set; }
    }

But the mapper code generated doesn't compile.

    public static SalesOrder AdaptTo(this SalesOrderDto p2, SalesOrder p3)
      {
          if (p2 == null)
          {
              return null;
          }
          SalesOrder result = p3 ?? new SalesOrder();
          
           //===========================================

              // Id, Total & Status are init properties in the SaleOrder type and fails to compile.
  
              result.Id = p2.Id;
              result.Total = p2.Total;
              result.Status = p2.Status;

           //===========================================

          return result;
          
      }

It is in this second variation of Adapt method that takes in both an Dto & Entity object, and tries to update the Entity object with the values from Dto object.

The other method generated works as expected.

public static SalesOrder AdaptToSalesOrder(this SalesOrderDto p1)
{
    return p1 == null ? null : new SalesOrder()
    {
        Id = p1.Id,
        Total = p1.Total,
        Status = p1.Status
    };
}

If this is a bigger piece of work, even a flag to avoid creating the second method will be an interim fix.

My CodeGenerationRegister as below if it helps.

public class ModelGenerationRegister : ICodeGenerationRegister
{
    public void Register(CodeGenerationConfig config)
    {

        config.AdaptTwoWays($"[name]Dto")
            .ForAllTypesInNamespace(typeof(SalesOrder).Assembly, "Mapster.Domain");

        config.GenerateMapper("[name]Mapper")
            .ForTypes(typeof(SalesOrder));
    }
    
}




Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions