Background
I am using a legacy database with all kinds of ugly corners. One bit is auditing. There is a table listing tablename/field combinations of fields that should have an audit trail. For example, if there is a row that has "WORKORDER" for the table name and "STATUS" for the fieldname, then I need to add row(s) to the auditing table whenever the Workorder.Status property changes in the application. I know the approach: NH events or interceptors, but I've got an issue to figure out before I get to that stage.
Question
What I need to know is how to get a list of key/value pairs for a single persistent class containing (a) the database field name and (b) the associated property name in the class. So for my example, I have a class called Workorder associated with a table called (no surprise) WORKORDER. I have a property on that Workorder class called CurrentStatus. The matching property in the WORKORDER table is STATUS. Notice the mismatch between the property name and table column name? I need to know the property name to access the before and after data for the audit. But I also need to know the backing column name so that I can query the stupid legacy "AuditTheseColumns" table.
What I've tried
in my application I change the Workorder.CurrentStatus from "TS" to "IP". I look in my audit tracking table and see that the WORKORDER.STATUS column is tracked. So after calling Session.SaveOrUpdate(workorder), I need to find the Workorder property associated with the STATUS column and do a Session.Save(auditRecord) telling it the old ("TS") and new ("IP") values.
As far as I can tell, you can get information about the class:
var fieldNames = new List<string>();
IClassMetadata classMetadata = SessionFactory(Resources.CityworksDatasource).GetClassMetadata(typeof(T));
int propertyCount = 0;
foreach (IType propertyType in classMetadata.PropertyTypes)
{
if (propertyType.IsComponentType)
{
var cp = (ComponentType)propertyType;
foreach (string propertyName in cp.PropertyNames)
{
fieldNames.Add(propertyName);
}
}
else if(!propertyType.IsCollectionType)
{
fieldNames.Add(classMetadata.PropertyNames[propertyCount + 1]);
}
propertyCount++;
}
And information about the table:
var columnNames = new List<string>();
PersistentClass mappingMeta = ConfigureCityworks().GetClassMapping(typeof(T));
foreach (Property property in mappingMeta.PropertyIterator)
{
foreach (Column selectable in property.ColumnIterator)
{
if (columnNames.Contains(selectable.Name)) continue;
columnNames.Add(selectable.Name);
}
}
But not at the same time. Any ideas? I'm at a loss where to look next.
How to get the database column / field names and class property names for an entity mapped by NHibernate:
using System;
using System.Collections.Generic;
using System.Reflection;
using NHibernate;
using NHibernate.Persister.Entity;
namespace Stackoverflow.Example
{
/// <summary>
/// NHibernate helper class
/// </summary>
/// <remarks>
/// Assumes you are using NHibernate version 3.1.0.4000 or greater (Not tested on previous versions)
/// </remarks>
public class NHibernateHelper
{
/// <summary>
/// Creates a dictionary of property and database column/field name given an
/// NHibernate mapped entity
/// </summary>
/// <remarks>
/// This method uses reflection to obtain an NHibernate internal private dictionary.
/// This is the easiest method I know that will also work with entitys that have mapped components.
/// </remarks>
/// <param name="sessionFactory">NHibernate SessionFactory</param>
/// <param name="entity">An mapped entity</param>
/// <returns>Entity Property/Database column dictionary</returns>
public static Dictionary<string, string> GetPropertyAndColumnNames(ISessionFactory sessionFactory, object entity)
{
// Get the objects type
Type type = entity.GetType();
// Get the entity's NHibernate metadata
var metaData = sessionFactory.GetClassMetadata(type.ToString());
// Gets the entity's persister
var persister = (AbstractEntityPersister)metaData;
// Creating our own Dictionary<Entity property name, Database column/filed name>()
var d = new Dictionary<string, string>();
// Get the entity's identifier
string entityIdentifier = metaData.IdentifierPropertyName;
// Get the database identifier
// Note: We are only getting the first key column.
// Adjust this code to your needs if you are using composite keys!
string databaseIdentifier = persister.KeyColumnNames[0];
// Adding the identifier as the first entry
d.Add(entityIdentifier, databaseIdentifier);
// Using reflection to get a private field on the AbstractEntityPersister class
var fieldInfo = typeof(AbstractEntityPersister)
.GetField("subclassPropertyColumnNames", BindingFlags.NonPublic | BindingFlags.Instance);
// This internal NHibernate dictionary contains the entity property name as a key and
// database column/field name as the value
var pairs = (Dictionary<string, string[]>)fieldInfo.GetValue(persister);
foreach (var pair in pairs)
{
if (pair.Value.Length > 0)
{
// The database identifier typically appears more than once in the NHibernate dictionary
// so we are just filtering it out since we have already added it to our own dictionary
if (pair.Value[0] == databaseIdentifier)
break;
d.Add(pair.Key, pair.Value[0]);
}
}
return d;
}
}
}
Usage:
// Get your NHiberate SessionFactory wherever that is in your application
var sessionFactory = NHibernateHelper.SessionFactory;
// Get an entity that you know is mapped by NHibernate
var customer = new Customer();
// Get a dictionary of the database column / field names and their corresponding entity property names
var propertyAndColumnNamesDictionary =
Stackoverflow.Example.NHibernateHelper.GetPropertyAndColumnNames(sessionFactory, customer);
Now if I understand correctly here is what you could do....
One way would be to read and parse the XML mapping files from the dll that are embedded before or even after the NHibernate session factory is build. This way you can get all the info you need from the XML files (with column corresponds to which property) and populate a global (probably static) collection of custom objects that will hold the entity's name and a dictionary with key the propery name and value the column name (or the other way around).
You can then access this global collection to get the info you need right after the call to SaveOrUpdate() as you described it.
The downside of this approach is that you need to write your own XML parsing logic to retrive the info you need from the XML mapping files.
An alternative would be to create a custom attribute to decorate each property of your entities in order to get the column name that corresponds to each property.
An example would be:
[ColumnName("MyColumn")]
public string Status { get; set; }
Using reflection you can easily get the property name and the from the attribute the column name that this property is mapped to.
The downside of this approach would be having to keep in sync your column names with the attribute values when the database schema is updated.
Related
I have an object in C# that I want to use as a primary key in a database that auto-increments when new objects are added. The object is basically a wrapper of a ulong value that uses some bits of the value for additional hints. I want to store it as a 'pure' ulong value in a database but I would like get an automatic conversion when the value is loaded / unloaded from DB. IE, apply the 'hint' bits to the value based on the table they come from.
I went on a journey of implementing my own IUserType object based on number of examples I found online ( tons of help on this forum ).
I have an ObjectId class that acts is an object ID
class ObjectIdType: IUserType
{
private static readonly NHibernate.SqlTypes.SqlType[] SQL_TYPES = { NHibernateUtil.UInt64.SqlType };
public NHibernate.SqlTypes.SqlType[] SqlTypes
{
get { return SQL_TYPES; }
}
public Type ReturnedType
{
get { return typeof(ObjectId); }
}
...
}
I have a mapping class that looks like this:
public class ObjectTableMap()
{
Id(x => x.Id)
.Column("instance_id")
.CustomType<ObjectIdType>()
.GeneratedBy.Native();
}
At this point I get an exception at config that Id can only be an integer. I guess that makes sense but I was half expecting that having the custom type implemented, the native ulong database type would take over and work.
I've tried to go down the path of creating a custom generator but its still a bit out of my skill level so I am stumbling though it.
My question is, is it possible for me to accomplish what I am trying to do with the mapping?
I think, it is not possible, because your mapping uses the native generator for the Id. This can only be used for integral types (and GUIDs). You can try to use assigned Ids with your custom type, so you are responsible for assigning the values to your Id property.
There is another alternative: Why not set your information bits on class level, instead depending on your table? Your entities represent the tables, so you should have the same information in your entity classes. Example:
class Entity
{
protected virtual ulong InternalId { get; set; } // Mapped as Id
public virtual ulong Id // This property is not mapped
{
get
{
var retVal = InternalId;
// Flip your hint bits here based on class information
return retVal;
}
}
}
You could also turn InternalId into a public property and make the setter protected.
I've been trying to map a clob field using Fluent NHibernate 1.2.0.712 against Oracle 10g. I'm using System.Data provider as it's available by default and was trying to avoid adding reference to ODP.Net due to previous client issues.
However, when I try to insert entities with mapped clob properties, I get the error:
ORA-01461: can bind a LONG value only for insert into a LONG column
I've tried to fix this by using the below convention, and decorating the appropriate property with [StringLength(4000)]:
public class StringLengthConvention : AttributePropertyConvention<StringLengthAttribute>
{
protected override void Apply(StringLengthAttribute attribute, IPropertyInstance instance)
{
instance.Length(attribute.MaximumLength);
}
}
This didn't work.
Then I tried the below using "TEXT", "CLOB" and "clob" values. Neither worked:
public class plaparteMappingOverride : IAutoMappingOverride<plaparte>
{
public void Override(AutoMapping<plaparte> mapping)
{
Map(x => x.disposiciones).CustomSqlTypeIs("TEXT");
}
}
Does anyone have further suggestions for this fix other than adding ODP as the provider?
For future reference: this post perfectly describes what causes this error and how you can solve it.
ORA-01461: can bind a LONG value only for insert into a LONG column
This error is not very helpful and goggling it will most likely result
in topics regarding oracle patches and the like. In reality this is a
bug with the microsoft oracle client driver. The driver mistakenly
infers the column type of the string being saved, and tries forcing
the server to update a LONG value into a CLOB/NCLOB column type. The
reason for the incorrect behavior is even more obscure and only
happens when all the following conditions are met.
when we set the IDbDataParameter.Value = (string whose length is : 4000 > length > 2000 )
when we set the IDbDataParameter.DbType = DbType.String
when DB Column is of type NCLOB/CLOB
Unfortunately NHibernate 2.0's default behavior is to do exactly the
above, making it quite more likely to run into this ugly bug when
using nhibernate and oracle.
Solution offered in the blog post: a custom NHibernate Oracle Driver:
/// <summary>
/// Initializes the parameter.
/// </summary>
/// <param name="dbParam">The db param.
/// <param name="name">The name.
/// <param name="sqlType">Type of the SQL.
protected override void InitializeParameter(System.Data.IDbDataParameter dbParam, string name, global::NHibernate.SqlTypes.SqlType sqlType)
{
base.InitializeParameter(dbParam, name, sqlType);
//System.Data.OracleClient.dll driver generates an exception
//we set the IDbDataParameter.Value = (string whose length: 4000 > length > 2000 )
//when we set the IDbDataParameter.DbType = DbType.String
//when DB Column is of type NCLOB/CLOB
//The Above is the default behavior for NHibernate.OracleClientDriver
//So we use the built-in StringClobSqlType to tell the driver to use the NClob Oracle type
//This will work for both NCLOB/CLOBs without issues.
//Mapping file will need to be update to use StringClob as the property type
if ((sqlType is StringClobSqlType))
{
((OracleParameter)dbParam).OracleType = OracleType.NClob;
}
}
I need to use Fluent-nHibernate against a table with a composite primary key (Azure Table, primary keys being (PartitionKey,RowKey) and I would like to map them with corresponding properties on the entity (or with a component property, if easier)
my table would look like:
{
PartitionKey PK,
RowKey PK,
[..]
}
and the entity
public class MyRecord
{
public virtual string PartitionKey{get;set;}
public virtual string RowKey{get;set;}
[...]
}
My current projet uses a custom nHibernate Driver targeting AzureTable.
I managed to make it work with ClassMap or XML mappings. Therefore I am sure that the driver is working. Furthermore, the azure table HTTP requests are correct using classmaps or XML declarations.
However I really need conventions, so this isn't an acceptable solution.
Finally, there is always the option to map only RowKey as a PK, even if the Datastore use (PartitionKey,RowKey). It works too, However it's not really satisfying as it introduces an unicity handling mismatch between nHibernate and the underlying datastore.
UPDATE:
I tried to build a custom IIdentityConvention. The IIdentityInstance.Column() method takes into account only the first call.
However, if I use reflection to add both columns to the underlying mapping field, the configuration build fails with an XML validation exception (attribute 'class' required)
I got it working today, but it's not pretty. It also doesn't use a convention. As I understand conventions, they're really meant for tweaking things after the main mapping has occurred. Adding mappings I believe is considered out of scope for conventions.
In my project I have a generic automapping-based initialization procedure that knows nothing of types, but has dependency-injected mapping overrides for composite keys. Not exactly your scenario, but it's a similar problem.
The way I got this to work through reflection was to get hold of the appropriate AutoPersistenceModel object. If you have code looking like this:
Fluently.Configure().Mappings(m => ...
The AutoPersistenceModel object would be m.AutoMappings.First()
From here, it's pretty serious reflection work, culminating in a call to a protected method inside FluentNHibernate. Here's the code I'm using:
private void Override(AutoPersistenceModel container,
Type type,
IEnumerable<KeyValuePair<string,string>> compositeKeys)
{
// We need to call container.Override<T>(Action<Automapping<T>> populateMap)
// Through reflection...yikes
var overrideMethod = typeof(AutoPersistenceModel)
.GetMethod("Override")
.MakeGenericMethod(type);
var actionFactoryMethod = typeof(FluentNHibernateInitializer)
.GetMethod("CompositeMapperFactory",
BindingFlags.Instance | BindingFlags.NonPublic)
.MakeGenericMethod(type);
var actionMethod = actionFactoryMethod
.Invoke(this, new object[] { compositeKeys });
overrideMethod.Invoke(container, new object[] {actionMethod});
}
private Action<AutoMapping<T>> CompositeMapperFactory<T>
(IEnumerable<KeyValuePair<string, string>> compositeKeys)
{
return new Action<AutoMapping<T>>(m =>
{
var compositeId = m.CompositeId();
foreach (var kvp in compositeKeys)
compositeId =
AddKeyProperty(
compositeId,
typeof(T).GetProperty(kvp.Key),
kvp.Value);
}
);
}
/// <summary>
/// Uses reflection to invoke private and protected members!
/// </summary>
/// <param name="compositeId"></param>
/// <param name="propertyInfo"></param>
/// <returns></returns>
private CompositeIdentityPart<T> AddKeyProperty<T>
(CompositeIdentityPart<T> compositeId,
PropertyInfo propertyInfo,
string column)
{
var member = FluentNHibernate.MemberExtensions.ToMember(propertyInfo);
var keyPropertyMethod = typeof(CompositeIdentityPart<T>)
.GetMethod("KeyProperty",
BindingFlags.Instance | BindingFlags.NonPublic);
return (CompositeIdentityPart<T>)
keyPropertyMethod
.Invoke(compositeId, new object[] { member, column, null });
}
I'm mapping my database tables using NHibernate with NHibernate.Mapping.Attributes library and I got stuck to get the Filter attributes to work.
Suppose a class A that has a set of objects of class B. So, I have, the following:
[NHibernate.Mapping.Attributes.Set(0, Inverse = true, Lazy = NHibernate.Mapping.Attributes.CollectionLazy.False)]
[NHibernate.Mapping.Attributes.Key(1, Column = "ClassAId")]
[NHibernate.Mapping.Attributes.OneToMany(2, Class = "ClassB, Assembly")]
public virtual ISet<ClassB> ClassBs { get; set; }
I want to create a filter on this collection to bring only class B objects that satisfy a given criteria, such as Status = 1.
How can I create such Filter?
The where parameter of the Set mapping should be able help you out. Per the documentation the where parameter:
where: (optional) specify an arbitrary
SQL WHERE condition to be used when
retrieving or removing the collection
(useful if the collection should
contain only a subset of the available
data)
So to filter on Status (assuming Status is a SQL column in the table mapped for ClassB - though this column does not have to be mapped in the NHibernate mapping).
[NHibernate.Mapping.Attributes.Set(0,...., Where = "Status = 1", .....)]
...
public virtual ISet<ClassB> ClassBs { get; set; }
I have a Oracle database and one of the fields is a date range field. It is basically just stored in the database as a VARCHAR(40) in the format YYYY/MM/DD-YYYY/MM/DD. I want to map it in nHibernate to a custom class I have created like this
public class DateTimeRange
{
public DateTimeRange(DateTime fromTime, DateTime toTime)
{
FromTime = fromTime;
ToTime = toTime;
}
public override string ToString()
{
return String.Format("{0} to {1}", FromTime.ToString("HH:mm:ss"), ToTime.ToString("HH:mm:ss"));
}
public DateTime FromTime { get; set; }
public DateTime ToTime { get; set; }
}
How can I map to custom classes like this?
You need to implement your own IUserType.
See this blog post for details. I'll also paste the relevant section below in case the blog disappears.
In NHibernate, a custom mapping type is a class that derives from either the IUserType or ICompositeUserType interfaces. These interfaces contain several methods that must be implemented, but for our purposes here, we’re going to focus on 2 of them. Consider the following.
public class TypeClassUserType : IUserType
{
object IUserType.NullSafeGet(IDataReader rs,
string[] names,
object owner) {
string name = NHibernateUtil.String.NullSafeGet(rs,
names[0]) as string;
TypeClassFactory factory = new TypeClassFactory();
TypeClass typeobj = factory.GetTypeClass(name);
return typeobj;
}
void IUserType.NullSafeSet(IDbCommand cmd,
object value,
int index) {
string name = ((TypeClass)value).Name;
NHibernateUtil.String.NullSafeSet(cmd, name, index);
}
}
Having created this class, I can now explicitly map the association between ActualClass and TypeClass as a simple property on the ActualClass mapping.
<property
name="Type"
column="TypeName"
type="Samples.NHibernate.DataAccess.TypeClassUserType,
Samples.NHibernate.DataAccess" />
As NHibernate is in the process of saving an instance of ActualType, it will load and create a new instance of TypeClassUserType and call the NullSafeSet method. As you can see from the method body, I am simply extracting the name from the mapped property (passed in as the value parameter) and setting the extracted name as the value of the parameter to be set in the database. The net result is that although the Type property of ActualClass is TypeClass in the domain model, only the Name property of the TypeClass object gets stored in the database. The converse is also true. When NHibernate is loading an instance of ActualType from the database and the finds a property of my custom mapping type, it loads my custom type and calls the NullSafeGet method. As you can see, my method gets the name from the returned data, calls my flyweight factory to get the correct instance of TypeClass, and then actually returns that instance. The type resolution process happens transparently to my data access classes (and even to NHibernate itself for that matter).