MapsterMapper / Mapster

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

Maping record types with properties and constructors #490

Open sajjadsaharkhan opened 2 years ago

sajjadsaharkhan commented 2 years ago

hi. thanks for this powerful and developer-friendly library I want to map to record with this senario:

using System.Text.Json;
using Mapster;

var sourceInstance = new MyDTOWithConstructor(2, "Sajjad");

var targetInstance = sourceInstance.Adapt<MyDTOWithPropertyAndConstructor>();
targetInstance.ParentId = 1; 

Console.WriteLine(JsonSerializer.Serialize(targetInstance));

record MyDTOWithPropertyAndConstructor(int Id, string Name)
{
    public int ParentId { get; set; }
}

record MyDTOWithConstructor(int Id, string Name);

it throws this exception:

Unhandled exception. Mapster.CompileException: Error while compiling
source=MyDTOWithConstructor
destination=MyDTOWithPropertyAndConstructor
type=Map
 ---> System.InvalidOperationException: No default constructor for type 'MyDTOWithPropertyAndConstructor', please use 'ConstructUsing' or 'MapWith'
   at Mapster.Adapters.BaseAdapter.CreateInstantiationExpression(Expression source, Expression destination, CompileArgument arg)
   at Mapster.Adapters.ClassAdapter.CreateInstantiationExpression(Expression source, Expression destination, CompileArgument arg)
   at Mapster.Adapters.ClassAdapter.CreateInlineExpression(Expression source, CompileArgument arg)
   at Mapster.Adapters.BaseAdapter.CreateInlineExpressionBody(Expression source, CompileArgument arg)
   at Mapster.Adapters.BaseAdapter.CreateExpressionBody(Expression source, Expression destination, CompileArgument arg)
   at Mapster.Adapters.BaseAdapter.CreateAdaptFunc(CompileArgument arg)
   at Mapster.TypeAdapterConfig.CreateMapExpression(CompileArgument arg)
   --- End of inner exception stack trace ---

Is there a way to map with this scenario without any additional code such as MapWith or change Mapster GlobalConfig or custom config for this case?