I have an object I'm trying to persist t开发者_如何学Pythono a legacy database with NHibernate. I have all of the relevant columns from a table mapped in my domain object, but have a few fields in the table that must be populated for the structure of the legacy db.
Following a few recommendations, I created and registered an NHibernate interceptor to do this for me.
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;
}
}
I've looked at this NHibernate add unmapped column in interceptor and Unmapped Columns in NHibernate? without finding the answer.
What I'm seeing is that I the OnSave method does fire, but I get nothing stored in the database (or the SQL query generated by NHibernate).
What am I doing wrong?
there is also this approach using virtual Properties and IPropertyAccessor. I used it in one of my projects in the domain model and for me its easier to declare it once in the mapping than everywhere where i open a session, which happens in several different projects (Application, imports, ETLs, integration of other programs)
I don't know a lot about how NHibernate Interceptors work, but I wouldn't expect that changing the passed in array variables would actually change anything external to the method. In order for the new arrays to end up back outside of the method, they would need to be passed by reference (ref
) parameters.
Looking at your first linked question (add unmapped column in interceptor), the first difference that jumps out is that at the end of his method, he calls the base method passing in the updated parameters (return base.OnSave(entity, id, state, propertyNames, types);
). Perhaps that would help?
精彩评论