I\'m attempting to audit/log the table and field names with their modified value.
My DTO is named differently to the database:
public class Emp
{
This is my way how to ask NHibernate to get all the information. In my case all the settings like column name, can Insert, can Update... are already there, and they could/should be used (even if only for documentation). So, the simplified, but fully working code snippets are below...
Firstly let's create some description object MappingDescription: , into which we will move all the settings and return it as a IList
public interface IMappingDescription
{
string PropertyName { get; }
string ColumnName { get; }
bool CanInsert { get; }
bool CanUpdate { get; }
Type PropertyType { get; }
bool IsLocalDateTime { get; }
}
And the static method, for any mapped persistent class TEntity:
public static IList<MappingDescription> ReadMappingInfo<TEntity>()
{
var entityType = typeof(TEntity);
var factory = ... // Get your ISessionFactory
var persister = factory.GetClassMetadata(entityType) as AbstractEntityPersister;
if (persister == null)
{
throw new InvalidCastException("NHibernate ISessionFactory did not return 'AbstractEntityPersister' on GetClassMetadata()");
}
// the set of Properties
var propertyNameList = persister.PropertyNames;
// the result
var map = new List<MappingDescription>();
// here we inject the mapping for ID property (execting one column per ID)
map.Add(new MappingDescription
{
PropertyName = Constants.Common.ID,
ColumnName = persister.KeyColumnNames.First(),
PropertyInfo = entityType.GetProperty(Constants.Common.ID),
});
// here we get all the settings for remaining mapped properties
foreach (var propertyName in propertyNameList)
{
var index = persister.GetPropertyIndex(propertyName);
// a check how to distinguish if we do work in UTC or Local
var isLocal = persister.GetPropertyType(propertyName) is NHibernate.Type.LocalDateTimeType
|| persister.GetPropertyType(propertyName) is NHibernate.Type.TimestampType;
var description = new MappingDescription
{
PropertyName = propertyName,
ColumnName = persister.GetPropertyColumnNames(propertyName).First(),
PropertyInfo = entityType.GetProperty(propertyName),
CanInsert = persister.PropertyInsertability[index],
CanUpdate = persister.PropertyUpdateability[index]
|| persister.PropertyTypes[index].IsCollectionType, // <idbag> has Updatebility false
IsLocalDateTime = isLocal,
};
map.Add(description);
}
return map;
}