should command handler throw only one event before save to EventStore?

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);
}

}

``

You can (should) save multiple events to the same stream with one call to Append.

/Peter

Ok so I should use AppendToStreamAsync not inside foreach loop but outside :slight_smile:

W dniu wtorek, 25 czerwca 2019 13:17:41 UTC+2 użytkownik Peter Hageus napisał:

Yes this vvv can be donne in a single call it takes an array :slight_smile: https://github.com/EventStore/ClientAPI.NetCore/blob/master/src/EventStore.ClientAPI.NetCore/IEventStoreConnection.cs#L78

foreach (var @event in events)
{
var eventData = “…”;

    await _eventStoreConnection.AppendToStreamAsync(stream, aggregate.Version, eventData);
}