K
K
kid-programmer2014-06-09 18:17:08
ASP.NET
kid-programmer, 2014-06-09 18:17:08

Where to open, save UnitOfWork?

Here I am trying to master the CQRS or Command/Query approach.
Internet code examples.
Example1.

public class CreateUserCommandHandler : EFCommandHandlerBase<CreateUserCommand, ApplicationDbContext>,
ICommandHandler<CreateUserCommand>
{
public CreateUserCommandHandler(ApplicationDbContext dbContext)
: base(dbContext)
{
}

public override void Execute(CreateUserCommand command)
{
Debug.WriteLine("CreateUserCommandHandler executed");

int id = DbContext.Users.Any() == false ? 1 : DbContext.Users.Max(x => x.Id) + 1;
User user = new User
{
Id = id,
FirstName = command.FirstName,
LastName = command.LastName,
Email = command.Email,
IsActive = false
};

DbContext.Users.Add(user);
DbContext.SaveChanges();

command.Id = user.Id;
}
}

it seems like this approach is not quite correct, because the command can be part of one transaction.
I also saw the implementation through the Repository
Example2
public class CreateStaffCommand : ICommand<CreateStaffCommandContext>
    {
        private readonly IRepository<Staff> _repository;

        public CreateStaffCommand(IRepository<Staff> repository)
        {
            _repository = repository;
        }

        public void Execute(CreateStaffCommandContext commandContext)
        {
            _repository.Add(new Staff(commandContext.Form.Name, commandContext.Form.Quantity));
        }
    }

I like this option better, but I can’t understand where it is better to save the transaction?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
iremezoff, 2014-06-19
@iremezoff

Hold on, it's well described here (another link from the Internet):
www.wekeroad.com/2014/03/04/repositories-and-unito...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question