将自己设为createby

时间:2015-06-01 15:41:10

标签: nhibernate fluent-nhibernate

用户既可以自己注册,也可以由其他用户创建。创建用户时,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();
     }
}

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

1 个答案:

答案 0 :(得分:2)

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();