我的前一篇随笔《使用NHibernate中的拦截器》中简单讲述了如何使用接口IInterceptor拦截CRUD操作。但没有区分开新增和修改操作。
对于public bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)会在Insert new object之前触发,而public void PreFlush(System.Collections.ICollection entities)则是Update old Object之前和Insert New Object之后都会触发的。为了记录下来明确的实体的insert和update操作,需要将其区分开。所以我查看了NHIbernate的源码,发现Insert  new object到了调用PreFlush后,其ID字段(属性)就有值了,而在OnSave时是为0或者null或者其它配置文件中定义的unsaved-value。通常为了简单,都是使用子动增长的字段作为ID的。所以我写了下面的代码来分别记录“新增”和“修改”的操作:
    }

上面代码中的private IEntityManager manager = null;是一个用来管理session的管理器,提供了一个属性public ISessionFactoryImplementor Factory,通过该属性才能方面地得知实体类的ID属性的名字:
使用NHibernate中的拦截器(续)public sealed class EntityManager : IEntityManager
}

获得ID属性的名字:
使用NHibernate中的拦截器(续)string idName = manager.Factory.GetPersister(type).IdentifierPropertyName;

于是现在可以比较粗略地记录下CRUD操作了……

相关文章:

  • 2021-06-24
  • 2021-12-22
  • 2021-09-02
  • 2021-05-19
  • 2021-12-30
猜你喜欢
  • 2021-05-23
  • 2021-09-17
  • 2021-12-31
  • 2022-01-15
  • 2021-07-24
相关资源
相似解决方案