简体   繁体   中英

NHibernate IInterceptor implementation(add properties to DB table that original domain class doesn't have)

How is possible to set some special column values when update/insert entities via NHibernate without extending domain classes with special properties?

For example: in my case I would like to get object and just moment before update/insert db add to that object some additional information (like user id or computer name) by using IInterceptor. In other words I would like to add a few columns to DB Table without specifying new properties in original object's class. Do I have to configure/change/add to my Object.hbm.xml or App.config in that case?

The problem is that I can't change my original objects and base classes.So I have to figure out if possible to add information to DB table without changing of the original objects (even no inherit from any base classes)

Example:

Original Object has : FirstName ,LastName,Birthday,Address properties

Customer.hbm.xml has:

<property name="FirstName" column="FirstName" type="string" not-null="true" length="64" />
<property name="LastName" column="LastName" type="string" not-null="true" length="64" />
<property name="Birthday" column="Birthday" type="DateTime" not-null="true"  />
<property name="Address" column="Address" type="string" not-null="true"  />

My Interceptor class has method:

public bool OnSave(object entity, object id, object[] state, string[] propertyNames, NHibernate.Type.IType[] types)

at that moment or even maybe before save I have to add to the DB Customer table additional 2 columns (Computer Name and User Name for example ) that propertyNames[] and state[] parameters don't have them from the beginning,so that should be done on the fly.

MY DB Customer table has all the columns that I have described above.

Thank you.

I haven't tried it, but you should be able to add the dynamic properties to the Configuration prior to factory creation. Then you can populate those values in your interceptor.

Ex, retrieve the relevant PersistentClass from config.ClassMappings, then add your properties to it.

private void AddProperty(
        PersistentClass pc, 
        string propertyName, 
        string columnName, 
        IType dataType)
    {
        SimpleValue val = new SimpleValue(pc.Table);
        Column col = new Column(dataType, 0);
        col.Name = columnName;
        val.AddColumn(col);
        val.Type = dataType;
        Property prop = new Property(val);
        prop.IsUpdateable = true;
        prop.Name = propertyName;
        prop.PropertyAccessorName = "nosetter.camelcase";
        prop.Cascade = "none";
        pc.AddNewProperty(prop);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM