是否可以在父事务中的PreInsert事件侦听器中保存新实体(在我的情况下为secondEntity)(在我的情况下为primaryEntity)? 我希望它们都在一个事务中执行,这意味着当primaryEntitysave失败时,我不想持久化secondEntity,当secondEntity失败时,我不想持久化primaryEntity。两个实体都必须存在于db中。
我的事件监听器代码
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;
}
在这种情况下,secondEntity不会持久保存到数据库。
当我在事件行的末尾添加内容时:
await innerSession.FlushAsync()
然后secondEntity被保留,但是firstEntity插入可能失败,然后由于db中仅存在一个实体,因此我的数据不一致。
当我尝试:await @event.Session.SaveAsync(secondEntity)
时出现错误:
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)