public void StoreEvents(object streamId, IEnumerable<object> events, long expectedInitialVersion)
{
events = events.ToArray();
var connectionString = ConfigurationManager.ConnectionStrings["main"].ConnectionString;
var serializedEvents =
events.Select(x => new Tuple<string, string>(x.GetType().FullName, JsonConvert.SerializeObject(x)));
using (var connection = new SqlCeConnection(connectionString))
{
connection.Open();
const string commandText = "SELECT TOP 1 CurrentSequence FROM Streams WHERE StreamId = @StreamId;";
long? existingSequence;
using (var command = new SqlCeCommand(commandText, connection))
{
command.Parameters.AddWithValue("StreamId", streamId.ToString());
var current = command.ExecuteScalar();
existingSequence = current == null ? (long?) null : (long) current;
if (existingSequence != null && ((long) existingSequence) > expectedInitialVersion)
throw new ConcurrencyException();
}
using (var transaction = new TransactionScope())
{
var nextVersion = InsertEventsAndReturnLastVersion(streamId, connection, expectedInitialVersion,
serializedEvents);
if(existingSequence == null)
StartNewSequence(streamId, nextVersion, connection);
else
{
UpdateSequence(streamId, expectedInitialVersion, nextVersion, connection);
}
transaction.Complete();
}
}
_bus.Publish(events);
}