Search code examples
c#.netnhibernatenhibernate-mapping

NHibernate determine key properties


I'm trying to make a generic DataTransfer between a Firebird and a MSSQL DB. Both Business-Libs contain the "same" classes wihch contain properties with an identical name.

My problem is, when I have a mapping with a composite key I don't know how much or which properties build the id.

So with a single ID it's easy, it's always the first property in my mapping files.

But what if I have a composite id? I would have to identify the properties which build the key.

I thought that could be done through de hbm.xml File but I'm not sure if that would work.

How I could determine which Properties build the key at runtime?


Solution

  • using the configuration you can ask each class for its identifyer property

    foreach(var clazz in config.ClassMappings)
    {
        var idProperties = clazz.IdentifierMapper.PropertyIterator
    }
    

    alternativly if you only want to query if the object already exists (and the entitytype could be only known at runtime)

    var classMetadata = sessionfactory.GetClassMetadata(obj.GetType());
    object id;
    if (classMetadata.IdentifierType.IsComponentType)
        id = obj;
    else
        id = classMetadata.GetIdentifier(obj, NHibernate.EntityMode.Poco);
    
    fromDatabase = session.Get(classMetadata.EntityName, obj);
    if (fromDatabase != null)
        // already exists