Saving new entity in PreInsert event listener in the parent transaction

40 views
Skip to first unread message

Pawel D

unread,
May 6, 2019, 9:20:13 PM5/6/19
to nhusers

Hi, I'm trying to save new entity (in my case secondEntity) in PreInsert event listener in the parent transaction (while saving primaryEntity in my situation). I want both of them to be saved in one transaction, that means when primaryEntitysave fails I don't want to persist secondEntity, when secondEntity fails I don't want to persist primaryEntity. Both entities must exist in db.


My event listener code

 public async Task<bool> OnPreInsertAsync(PreInsertEvent @event, CancellationToken cancellationToken)
    {
        using (var innerSession = @event.Session.SessionWithOptions().Connection().OpenSession())
        {
            var secondEntity = new Entity();

            await innerSession.SaveAsync(secondEntity);
        }

        return false;
    }

In that situation, secondEntity doesn't persist to database. When I add at the end of event line: await innerSession.FlushAsync() then secondEntity is persisted, but firstEntity insert can fails, then my data is inconsistens beceuse only one entity is present in db.


When I try: await @event.Session.SaveAsync(secondEntity) then I got error:


System.InvalidOperationException : Collection was modified; enumeration operation may not execute.
   at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
   at NHibernate.Engine.ActionQueue.ExecuteActionsAsync(IList list, CancellationToken cancellationToken)
   at NHibernate.Engine.ActionQueue.ExecuteActionsAsync(CancellationToken cancellationToken)
   at NHibernate.Engine.ActionQueue.ExecuteActionsAsync(CancellationToken cancellationToken)
   at NHibernate.Event.Default.AbstractFlushingEventListener.PerformExecutionsAsync(IEventSource session, CancellationToken cancellationToken)
   at NHibernate.Event.Default.DefaultFlushEventListener.OnFlushAsync(FlushEvent event, CancellationToken cancellationToken)
   at NHibernate.Impl.SessionImpl.FlushAsync(CancellationToken cancellationToken)
   at NHibernate.Impl.SessionImpl.BeforeTransactionCompletionAsync(ITransaction tx, CancellationToken cancellationToken)
   at NHibernate.Transaction.AdoTransaction.CommitAsync(CancellationToken cancellationToken)
Reply all
Reply to author
Forward
0 new messages