views:

39

answers:

0

Hi, 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