我的应用程序具有以下实体:
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; }
}
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);
}
}
UsersLog表只记录对用户所做的任何更改。我正在尝试使用NHibernate事件侦听器自动连接这个。我已经设置了成功调用以下2个方法的配置:
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);
}
编辑(这里是InsertLog方法):
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)
}
当我更新一个记录时,一个日志被成功插入,但是当我插入一个记录时,我得到一个错误,告诉我UsersLog表中的UserID不能为null。我玩过一些不同的变化,但似乎没有什么工作。
如果有人能告诉我怎么做我会非常感激的。谢谢