如何配置NHibernate的事件侦听器的更新和保存? [英] How to configure NHIbernate event listeners for Update and Save?
问题描述
这是我刚才的问题如何NHibernate的实体实施LASTUPDATE <? 。/ A>
Following on from my previous question How to implement LastUpdate in NHibernate Entities?.
我在我的数据库我的审计表两列:
I have two columns on my audited tables in my database:
-
创建日期时间默认GETDATE()不为空
(该行的创建日期)
LASTUPDATE日期时间空
(将datetime此行的最后更新)
lastUpdate datetime null
(the datetime this row was last updated)
我要创建的更新NHibernate的唯一监听器,因为数据库引擎需要照顾的新记录的默认约束。我试图创建与此代码自定义监听器:
I want to create a listener for updates only in NHibernate, because the database engine takes care of new records with the default constraint. I tried to create a Custom listener with this code:
public class CustomUpdateEventListener : DefaultSaveOrUpdateEventListener
{
protected override object PerformSaveOrUpdate(SaveOrUpdateEvent evt)
{
var entity = evt.Entity as IAuditableEntity;
if (entity != null)
{
ProcessEntityBeforeUpdate(entity);
}
return base.PerformSaveOrUpdate(evt);
}
internal virtual void ProcessEntityBeforeUpdate(IAuditableEntity entity)
{
entity.UpdateDate = DateTime.Now;
}
}
和其更新的伟大工程,但它也得到为保存
运行事件(当我新行添加到数据库中)。我不希望它火的新行。我试图修改代码来听更新
事件仅但我不能工作了。
and it works great for updates, but it also gets run for Save
events (when I add new rows to the database). I don't want it to fire for new rows. I tried to change the code to listen to Update
events only but I can't work it out.
我试图改变类从 DefaultUpdateEventListener
继承,但有没有 UpdateEvent
(仅 SaveOrUpdate
事件或 PreUpdate
或 PostUpdate
)
I tried to change the class to inherit from DefaultUpdateEventListener
but there's no UpdateEvent
(only SaveOrUpdate
events or PreUpdate
or PostUpdate
)
我不知道我是否应该使用 PreUpdate
事件,并让我的听众从 DefaultUpdateEventListener
继承后来我'不能确定我需要重写哪种方法。没有更新
方法重写。
I'm wondering if I should use the PreUpdate
event and making my listener inherit from DefaultUpdateEventListener
but then I'm not sure which method I need to override. There is no Update
method to override.
推荐答案
您可以让您的类实现IPreUpdateEventListener接口(及其OnPreUpdate方法)。然后通过配置类添加到会话中的事件listerners:
You could make your class implement the IPreUpdateEventListener interface (and its OnPreUpdate method). Then add your class to the session event listerners through the config:
NHibernate.Cfg.Configuration cfg = new NHibernate.Cfg.Configuration();
cfg.EventListeners.PreUpdateEventListeners =
new IPreUpdateEventListener[] {new YourEventListener()};
sessionFactory = cfg.BuildSessionFactory();
这篇关于如何配置NHibernate的事件侦听器的更新和保存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!