Exploring nhibernate mapping

后端 未结 1 2016
傲寒
傲寒 2021-01-27 06:47

A code generator needs to extract and generate some metadata from nhibernate mappings, I am wondering how nhibernate store relations.

For many to one relation how the o

相关标签:
1条回答
  • 2021-01-27 07:22

    Configuration, and later ISessionFactory build from it, are keeping information about persisters. They could represent entities or collections.

    Here we can see what we could get about any persisted class:

    • How do you get the database column name

    The class persister:

    var entityType = typeof(TEntity);
    var factory = ... // Get your ISessionFactory
    var persister = factory.GetClassMetadata(entityType) as AbstractEntityPersister;
    

    And we also can observe collection persisters

    • Test a collection is Many to many or many to one

    the collection persister:

    // the Abstract collection persister
    var collectionPersister = factory
        .GetCollectionMetadata(roleName) as AbstractCollectionPersister;
    
    // here we go:
    var isManyToMany = collectionPersister.IsManyToMany;
    var isOneToMany = collectionPersister.IsOneToMany;
    

    So, in general, what is mapped, it is represented as persister. Hope it helps

    EXTEND, find out one-to-one

    Based on the stuff above, the explicit search for one-to-one could be like:

    var persister = factory.GetClassMetadata(entityType) as AbstractEntityPersister;
    var propertyNameList = persister.PropertyNames;
    
    foreach (var propertyName in propertyNameList)
    {
        // many info is in collections, so we need to know the index
        // of our property
        var index = persister.GetPropertyIndex(propertyName);
    
        // with index, we can work with the mapped type
        var type = persister.PropertyTypes[index];
    
        // if the type is OneToOne... we can observe
        if(type is NHibernate.Type.OneToOneType)
        {
            Console.Write(type.IsAssociationType);
            Console.Write(type.IsAnyType);
            Console.Write(type.IsMutable);
            Console.Write(type.IsCollectionType);
            Console.Write(type.IsComponentType);
            Console.Write(type.ReturnedClass);
            ...
            // many other interesting and useful info could be revealed
        }
    }
    
    0 讨论(0)
提交回复
热议问题