【发布时间】:2018-02-06 20:13:57
【问题描述】:
我正在尝试将 CQRS+ES 应用于我的宠物项目。但我不确定如何处理复杂的命令。
假设我有一个网页,您可以在其中创建一个新的User。因此,在您的页面上,您只需输入名字、姓氏、用户名和密码。但是,您必须还向该用户添加一个或多个Roles。当点击 Save 按钮时,会触发以下命令CreateUserWithRolesCommand。
以下是命令处理程序中的有效方法吗?
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
}
}
【问题讨论】:
标签: design-patterns domain-driven-design cqrs