我将NHibernate与Fluent NHibernate一起使用,并注册一个SaveOrUpdate类型的Eventlistener。
private static ISessionFactory CreateSessionFactory()
{
return Fluently.Configure()
.ExposeConfiguration(c => c.SetListener(NHibernate.Event.ListenerType.SaveUpdate, new SaveEventListener()))
.BuildSessionFactory();
}
听众看起来像这样:
public class SaveEventListener : ISaveOrUpdateEventListener
{
public void OnSaveOrUpdate(SaveOrUpdateEvent _event)
{
object entity = _event.Entity;
if (entity is CreatableEntity)
{
CreatableEntity cEntity = entity as CreatableEntity;
if (cEntity != null)
{
if (cEntity.IsNew)
{
cEntity.TimeStamp = TimeStamp.New();
}
else
{
cEntity.TimeStamp = TimeStamp.Updated(cEntity.TimeStamp);
}
}
}
}
}
侦听器成功调用f.ex.在这种方法中:
public void Create(string firstName, string lastName, string organization)
{
session = GetCurrentSession();
ITransaction transaction = session.BeginTransaction();
try
{
Person person = new Person(firstName, lastName, organization);
session.SaveOrUpdate(person); //at this point
transaction.Commit();
}
catch
{
transaction.Rollback();
throw;
}
finally
{
session.Close();
}
}
但数据库未更新(如果没有注册侦听器,这可以正常工作)。任何帮助表示赞赏。
答案 0 :(得分:1)
您应该调用默认事件侦听器。
class SaveEventListener : DefaultSaveOrUpdateEventListener
{
public override void OnSaveOrUpdate(SaveOrUpdateEvent _event)
{
// ....
base.OnSaveOrUpdate(event);
}
}