将类映射到多个表

时间:2013-01-23 23:16:22

标签: .net nhibernate fluent-nhibernate nhibernate-mapping

我有一个无法映射到一个显式表的类。它映射到的表取决于使用它的上下文。基本上它应该像我试图将IDictionary<string, int>绑定到表格一样。

// this is a mapped entity, with a Guid Id, but it can't be mapped to one explicit table
public class NoTableClass : Entity<Guid>
{

}

// the table that this class gets its MyCollectionContext1 from depends on the HasMany mapping for that property
public class MappedClass1 : Entity<Guid>
{
    public IEnumerable<NoTableClass> MyCollectionContext1 { get; set; }
}

// the table that this class gets its MyCollectionContext2 from depends on the HasMany mapping for that property
public class MappedClass2 : Entity<Guid>
{
    public IEnumerable<NoTableClass> MyCollectionContext2 { get; set; }
}


// Mapping overrides

public void Override(AutoMapping<MappedClass1> mapping)
{
    mapping.HasMany(Reveal.Member<MappedClass1, IEnumerable<NoTableClass>>("MyCollectionContext1"))
        .Table("Table1")
        .Access.Field()
        .Cascade.AllDeleteOrphan();
}

public void Override(AutoMapping<MappedClass2> mapping)
{
    mapping.HasMany(Reveal.Member<MappedClass2, IEnumerable<NoTableClass>>("MyCollectionContext2"))
        .Table("Table2")
        .Access.Field()
        .Cascade.AllDeleteOrphan();
}   

当集合具有自定义类时,NHibernate似乎忽略了.Table()映射方法。我不明白为什么可以用这种方式映射简单类型的字典,但是带有自定义类的集合不能。

注意:我有理由不想使用继承/泛型来解决这个问题,并且不希望为我映射到的每个表都有一个具体的类型。我们有一个使用泛型的工作解决方案,但它为我们创造了其他问题。

1 个答案:

答案 0 :(得分:2)

我认为您尝试做的事情可以通过组件来实现:

public static void Override(AutoMapping<MappedClass1> mapping) {
    mapping.HasMany(Reveal.Member<MappedClass1, IEnumerable<NoTableClass>>("MyCollectionContext1"))
            .Component(c => {
                c.Map(x => x.Id);
                c.Map(x => x.Name);
            })
            .Table("Table1")
            .Cascade.AllDeleteOrphan();
}

public static void Override(AutoMapping<MappedClass2> mapping) {
    mapping.HasMany(Reveal.Member<MappedClass2, IEnumerable<NoTableClass>>("MyCollectionContext2"))
            .Component(c => {
                c.Map(x => x.Id);
                c.Map(x => x.Name);
            })
            .Table("Table2")
            .Cascade.AllDeleteOrphan();
}

以下代码:https://gist.github.com/4620069