探索nhibernate映射

时间:2014-08-30 05:42:44

标签: c# nhibernate nhibernate-mapping

代码生成器需要从nhibernate映射中提取并生成一些元数据,我想知道nhibernate如何存储关系。

对于多对一关系,对方如何存储(一对一部分)

域名模型:

public class Person
{
  public Detail {get;set;}
}

public class Detail 
{
  public Person {get;set;}
}

遍历地图:

PersistentClass map = _config.GetClassMapping(typeof(Person));
Property prop = map.GetProperty("Detail");

// how to find Associated Property (I.E. 'Detail.Person')

1 个答案:

答案 0 :(得分:0)

配置以及后来构建的ISessionFactory正在保留有关持久性的信息。它们可以代表实体或集合。

在这里,我们可以看到我们可以获得的任何持久化类:

班级持有人:

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

我们也可以观察收集持久性

集合持久性:

// the Abstract collection persister
var collectionPersister = factory
    .GetCollectionMetadata(roleName) as AbstractCollectionPersister;

// here we go:
var isManyToMany = collectionPersister.IsManyToMany;
var isOneToMany = collectionPersister.IsOneToMany;

因此,通常,映射的内容,它表示为persister。希望它有所帮助

EXTEND,找出one-to-one

根据上述内容,one-to-one的显式搜索可能如下:

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
    }
}