保存对象NHibernate的IInterceptor
-
18-09-2019 - |
题
我建立一个IInterceptor在我的域模型ILoggable对象。而就OnFlushDirty事件,我试图保存日志(审计)。但是,尽管这样,我的代码进入一个无限循环。
_logrepository.Save(日志)调用OnFlushDirty即使日志不是ILoggable对象(这是因为实体仍然是以前的对象)
有没有办法使用.Save(无需打开另一个会话)的IInterceptor的方式,或者我怎么在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)被打开另一个交易和commiting它。 所以,我改变logrepository.Save(日志)不打开和提交另一个事务但使用打开的事务。
不隶属于 StackOverflow