开发者

NHibernate Auditing - PostInsert Not Working

开发者 https://www.devze.com 2023-01-15 21:41 出处:网络
My application has the following entities: public class User { public virtual int UserID { get; set; } public virtual string UserName { get; set; }

My application has the following entities:

public class User
{
    public virtual int UserID { get; set; }
    public virtual string UserName { get; set; }
    public virtual IList<UserLog> Log { get; private set; }

    public User()
    {
        Log = new List<UserLog>();
    }
}

public class UserLog
{
    public virtual int UserLogID { get; set; }
    public virtual User User { get; set; }
    public virtual string UserName { get; set; }
    public virtual DateTime DateCreated { get; set; }
}

With the following fluent mappings:

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("Users");
        Id(x => x.UserID);
 开发者_开发百科       Map(x => x.UserName);
        HasMany(x => x.Log)
            .KeyColumn("UserID")
            .OrderBy("DateCreated")
            .Inverse()
            .Cascade.All();
    }
}

public class UserLogMap : ClassMap<UserLog>
{
    public UserLogMap()
    {
        Table("UsersLog");
        Id(x => x.UserLogID);
        References(x => x.User, "UserID");
        Map(x => x.UserName);
        Map(x => x.DateCreated);
    }
}

The UsersLog table simply logs any changes which are made to the User. I'm trying to hook this up automatically using the NHibernate event listeners. I have setup my configuration which successfully calls the following 2 methods:

public void OnPostInsert(PostInsertEvent @event)
{
    if (@event.Entity is User)
        InsertLog(@event.Entity);
}

public void OnPostUpdate(PostUpdateEvent @event)
{
    if (@event.Entity is User)
        InsertLog(@event.Entity);
}

Edit (here is the InsertLog method):

private void InsertLog(object entity)
{
    var context = ServiceLocator.Current.GetInstance<IDataContext>();
    var user = (User)entity;
    context.Repository<UserLog>().Insert(new UserLog
    {
        User = user,
        UserName = user.UserName,
        DateCreated = DateTime.UtcNow
    }); // Insert calls ISession.SaveOrUpdate(entity)
}

When i update a record a log is successfully inserted but when i insert a record i get an error telling me the UserID cannot be null in the UsersLog table. I've played around with a few different variations but nothing seems to work.

I'd really appreciate it if someone could show me how this can be done. Thanks


Solution posted in question comments. I simply had to use:

@event.Session.GetSession(NHibernate.EntityMode.Poco).Save(...);

to save the user instead of accessing the repository.

0

精彩评论

暂无评论...
验证码 换一张
取 消