我的应用程序包含以下实体:
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事件侦听器自动挂钩。我已经设置了我的配置,成功调用了以下两种方法:
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)
}
当我更新记录时,日志成功插入,但是当我插入记录时,我收到一条错误,告诉我UserLog表中的UserID不能为空。我玩了几个不同的变化,但似乎没有任何效果。
如果有人能告诉我这是怎么做的,我真的很感激。感谢
答案 0 :(得分:5)
解决方案发布了问题评论。我只需要使用:
@event.Session.GetSession(NHibernate.EntityMode.Poco).Save(...);
保存用户而不是访问存储库。