将自己设置为 createby

setting self as createby

用户可以自己注册,也可以由其他用户创建。创建用户时,CreateBy 设置为创建新用户的用户。当用户注册时,我们要将 CreateBy 设置为正在注册的用户。

public class User
{
    int Id;
    string Username;
    User CreateBy;
}

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Id(x=>x.Id);
        Map(x=>x.Usernam);
        References(x=>x.CreateBy)
            .Cascade.All()
            .Not.LazyLoad();
     }
}

如果数据库字段 'CreateBy' 设置为 not null,我们如何将 CreateBy 设置为尝试注册的用户?

public class User : Auditable
{
    int Id;
    string Username;
}

public class Auditable :  IAuditable
{
    public virtual int CreatedBy { get; set; }
}

public class AuditEventListener : IPreInsertEventListener
{
    public bool OnPreInsert(PreInsertEvent @event)
    {
        var audit = @event.Entity as IAuditable;
        if (audit == null)
            return false;

       var userId = [Your-current-user].Current().UserId; 
       Set(@event.Persister, @event.State, "CreatedBy", userId); 
       audit.CreatedBy= userId;    
       return false;
   }

   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;
   }
}

.Mappings(...)
.ExposeConfiguration(cfg => cfg.EventListeners.PreInsertEventListeners = new IPreInsertEventListener[] { new Convention.AuditEventListener() })
.BuildSessionFactory();