I have the error : WrongExpectedVersion - Expected version: -1, Current version: 0
I know why (I throw two events in command handler CreateOrderCommandHandler) but I don’t know what I should change in my code, I am new in DDD. Should my command handler throw one event or what?
This is pseudo code:
In CreateOrderCommandHandler I created the aggregate Order with items:
var order = new Order(customerId); // inside I rise throw event OrderCreatedEvent
foreach (var item in request.OrderItems)
{
order.AddOrderItem(item.ProductId, item.Quantity, item.Price); // inside I rise throw event OrderItemAddedEvent
}
// then I am trying save events to EventStore
``
The aggregate Order:
public class Order : AggregateRoot
{
public Guid Id;
public int Version = -1;
public Order(Guid customerId)
{
ApplyChange(new OrderCreatedEvent(Guid.NewGuid(), customerId));
}
public void AddOrderItem(Guid productId, int quantity, decimal price)
{
ApplyChange(new OrderItemAddedEvent(Id, productId, quantity, price));
}
}
``
Then I save events to the EventStore:
public async Task Save(T aggregate) where T : AggregateRoot
{
var events = aggregate.GetUncommittedEvents();
var stream = "...";
foreach (var @event in events)
{
var eventData = "...";
await _eventStoreConnection.AppendToStreamAsync(stream, aggregate.Version, eventData);
}
}
``