[英]saving objects in NHibernate IInterceptor
我在域模型中為ILoggable對象設置了一個IInterceptor。 在OnFlushDirty事件上,我正在嘗試保存日志(審核)。 但是在執行此操作時,我的代碼進入了無限循環。
_logrepository.Save(log)調用OnFlushDirty,即使log不是ILoggable對象(這是因為實體仍然是前一個對象)
有沒有一種方法可以在IInterceptor中使用.Save(無需打開另一個會話),或者如何在IInterceptor中將日志插入數據庫?
public override bool OnFlushDirty(object entity, object id, object[] currentState, object[] previousState, string[] propertyNames, NHibernate.Type.IType[] types)
{
//find diffs, log each change
if (entity is ILoggable && entity is NamedEntity)
{
var namedEntity = entity as NamedEntity;
for (var i = 0; i < currentState.Count(); i++)
{
if (currentState[i] != previousState[i])
{
var log = new Log()
{
Description = "update",
InDate = namedEntity.ModifiedDate.Value,
ItemId = namedEntity.Id,
ItemType = namedEntity.GetType().Name,
NewValue = currentState[i].ToString(),
OldValue = previousState[i].ToString(),
PropertyName = propertyNames[i],
UserId = namedEntity.ModifiedByUserId.Value
};
// calling save calls onflushdirty again, where entity is not log, but the same entity of the first call
ObjectFactory.GetInstance().Save(log);
}
}
}
return base.OnFlushDirty(entity, id, currentState, previousState, propertyNames, types);
}
好的,我知道了,我的問題是_logrepository.Save(log)正在打開另一個交易並提交它。 因此,我更改了logrepository.Save(log)而不是打開並提交另一個事務,而是使用一個打開的事務。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.