Martin Rohwedder
Martin Rohwedder

Reputation: 1751

Map request object and add extra string to destination object using mapster

I am trying to Map a request object plus and extra string to another object using C# Mapster. However I cant seem to find a solution to do it.

The user sends a request and the controller recieves a object from this class

public record CreateTaskRequest(
    string Message);

In the controller I am also fetching a username. This CreateTaskRequest and the username string I have fetched, I want to send to an object of my CreateTaskCommand class which looks like this

public record CreateTaskCommand(
    string Message,
    string Username) : IRequest<TaskResult>;

In my controller I am atm. newing this CreateTaskCommand class and sending it with MediatR to my handler. This works like it should. My controller method looks like this.

[HttpPost("Task/Create")]
public async Task<IActionResult> CreateTask(CreateTaskRequest request)
{
    var username = User.FindFirstValue(ClaimTypes.GivenName)!;

    var taskResult = await _mediator.Send(new CreateTaskCommand(request.Message, username));

    return Ok("Task Created");
}

I would like to use Mapster to map my CreateTaskRequest object and username to CreateTaskCommand object.

How can I do that?

I already made a mapping configuration class ready for configuring the mapping. It looks like this.

public class TodolistMappingConfiguration : IRegister
{
    public void Register(TypeAdapterConfig config)
    {
        // This code doesnt Map correctly.
        //config.NewConfig<CreateTaskRequest, CreateTaskCommand>();
    }
}

Thanks for the help in advance.

Upvotes: 0

Views: 1132

Answers (1)

Martin Rohwedder
Martin Rohwedder

Reputation: 1751

I found an answer after some help elsewhere (Facebook groups). I am sharing my solution here, so it might help others.

public class TodolistMappingConfiguration : IRegister
{
    public void Register(TypeAdapterConfig config)
    {
        config.NewConfig<CreateTaskRequest, CreateTaskCommand>()
            .Map(dest => dest.Username, src => MapContext.Current!.Parameters["username"]);
    }
}

And then I can map it in my controller like this

[HttpPost($"Task/Create")]
public async Task<IActionResult> CreateTask(CreateTaskRequest request)
{
    var username = User.FindFirstValue(ClaimTypes.GivenName)!;

    var command = _mapper.From(request).AddParameters("username", username).AdaptToType<CreateTaskCommand>();
    var taskResult = await _mediator.Send(command);

    return Ok("Task Created");
}

Upvotes: 2

Related Questions