将未映射的数据添加到NHibernate

时间:2011-08-25 19:30:29

标签: nhibernate interceptor

我有一个对象,我试图用NHibernate持久保存到遗留数据库。我有一个映射在我的域对象中的表中的所有相关列,但是在表中有一些必须填充旧数据库结构的字段。

根据一些建议,我创建并注册了一个NHibernate拦截器来为我做这个。

 public class CustomLineItemInterceptor : EmptyInterceptor
 {

  public override bool OnSave(object entity, object id, object[] state, string[] propertyNames, IType[] types)
  {
    var lineItem = entity as SomeCustomLineItem;

    if (lineItem == null)
    return false;


    List<string> propertyNameList = propertyNames.ToList();
    List<IType> typeList = types.ToList();
    List<object> stateList = state.ToList();

    propertyNameList.Add("Source");   // the unmapped column in the database
    typeList.Add(NHibernateUtil.String);
    stateList.Add("My Application's Name");  // the value I need to persist

    state = stateList.ToArray();
    propertyNames = propertyNameList.ToArray();
    types = typeList.ToArray();

    return true;
    }
}

我在没有找到答案的情况下查看了此NHibernate add unmapped column in interceptorUnmapped Columns in NHibernate?

我所看到的是OnSave方法确实触发了,但我没有在数据库中存储任何内容(或NHibernate生成的SQL查询)。

我做错了什么?

2 个答案:

答案 0 :(得分:3)

还有使用虚拟属性和IPropertyAccessor的this方法。我在域模型中的一个项目中使用它,对我来说,在映射中比在我打开会话的任何地方更容易声明它,这发生在几个不同的项目中(应用程序,导入,ETL,其他程序的集成)

答案 1 :(得分:1)

我不太了解NHibernate拦截器是如何工作的,但我不希望改变传入的数组变量实际上会改变方法外部的任何东西。为了使新数组最终返回到方法之外,需要通过引用(ref)参数传递它们。

查看您的第一个linked question (add unmapped column in interceptor),跳出的第一个区别是,在他的方法结束时,他调用基本方法传递更新的参数(return base.OnSave(entity, id, state, propertyNames, types);)。也许这会有所帮助吗?