mardi 6 février 2018

Persisting multiple things a single command handler with CQRS

I'm trying to apply CQRS+ES to my pet project. But I'm not sure how to handle complex commands.

Suppose I have a web page where you can create a new User. So on that you page you simply enter firstname, lastname, username and password. But, you must also add one or more Roles to that user. When hitting the Save button then the following command is fired CreateUserWithRolesCommand.

Is the following a valid approach in a command handler?

public class CreateUserWithRolesCommandHandler : ICommandHandler<CreateUserWithRolesCommand>
{
    private readonly AppDbContext _context;

    public UserCommandHandler(AppDbContext context)
    {
        _context = context;
    }

    public void Handle(CreateUserCommand command)
    {
        // todo: begin db transaction 

        var user = new User();
        user.Username = command.Username;
        user.Password = command.Password;
        user.Firstname = command.Firstname;
        user.Lastname = command.Lastname;
        _context.User.Add(user);
        _context.Save();

        // After save, get user id
        van userId = user.Id;

        van userRoles = new UserRoles;

        // Ommiting foreach loop and just taking the 
        // first role to keep the example simpler
        userRole.RoleId = command.Roles.First().RoleId;
        userRole.UserId = userId;
        _context.UserRoles.Add(userRole);
        _context.Save();

        // end db transaction and commit if all successful
    }
}

Aucun commentaire:

Enregistrer un commentaire