要使用NHibernate实现ChangeTime和ChangeUser列,您需要遵循以下步骤:
public class MyEntity
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual DateTime ChangeTime { get; set; }
public virtual string ChangeUser { get; set; }
}
<class name="MyEntity" table="MyEntity">
<id name="Id" column="Id">
<generator class="identity" />
</id>
<property name="Name" column="Name" />
<property name="ChangeTime" column="ChangeTime" />
<property name="ChangeUser" column="ChangeUser" />
</class>
</hibernate-mapping>
public class AuditEventListener : IPreUpdateEventListener, IPreInsertEventListener
{
public bool OnPreUpdate(PreUpdateEvent @event)
{
SetChangeTimeAndUser(@event.Persister, @event.State, @event.Session);
return false;
}
public bool OnPreInsert(PreInsertEvent @event)
{
SetChangeTimeAndUser(@event.Persister, @event.State, @event.Session);
return false;
}
private void SetChangeTimeAndUser(IEntityPersister persister, object[] state, ISession session)
{
int changeTimeIndex = Array.IndexOf(persister.PropertyNames, "ChangeTime");
int changeUserIndex = Array.IndexOf(persister.PropertyNames, "ChangeUser");
if (changeTimeIndex >= 0)
{
state[changeTimeIndex] = DateTime.UtcNow;
}
if (changeUserIndex >= 0)
{
state[changeUserIndex] = session.SessionFactory.CurrentSessionContext.Session.GetSessionImplementation().Connection.ConnectionString;
}
}
}
var configuration = new Configuration();
configuration.Configure();
configuration.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { new AuditEventListener() };
configuration.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] { new AuditEventListener() };
现在,每当您使用NHibernate插入或更新MyEntity实例时,ChangeTime和ChangeUser列将自动填充。
领取专属 10元无门槛券
手把手带您无忧上云