Mysql
 sql >> Datenbank >  >> RDS >> Mysql

NHibernate IPreUpdateEventListener, IPreInsertEventListener speichert nicht in DB

Die Antwort würde in diesen Zitaten aus Ayendes Artikel versteckt/offenbart werden

Dies ist der Code, der zeigt, wie es geht, aus demselben Artikel:

public class AuditEventListener : IPreUpdateEventListener, IPreInsertEventListener
{
    public bool OnPreUpdate(PreUpdateEvent @event)
    {
        var audit = @event.Entity as IHaveAuditInformation;
        if (audit == null)
            return false;

        var time = DateTime.Now;
        var name = WindowsIdentity.GetCurrent().Name;

        Set(@event.Persister, @event.State, "UpdatedAt", time);
        Set(@event.Persister, @event.State, "UpdatedBy", name);

        audit.UpdatedAt = time;
        audit.UpdatedBy = name;

        return false;
    }

    public bool OnPreInsert(PreInsertEvent @event)
    {
        var audit = @event.Entity as IHaveAuditInformation;
        if (audit == null)
            return false;


        var time = DateTime.Now;
        var name = WindowsIdentity.GetCurrent().Name;

        Set(@event.Persister, @event.State, "CreatedAt", time);
        Set(@event.Persister, @event.State, "UpdatedAt", time);
        Set(@event.Persister, @event.State, "CreatedBy", name);
        Set(@event.Persister, @event.State, "UpdatedBy", name);

        audit.CreatedAt = time;
        audit.CreatedBy = name;
        audit.UpdatedAt = time;
        audit.UpdatedBy = name;

        return false;
    }

Und hier ist das magische Set()

private void Set(IEntityPersister persister, object[] state
       , string propertyName, object value)
{
    var index = Array.IndexOf(persister.PropertyNames, propertyName);
    if (index == -1)
        return;
    state[index] = value;
}