Two collection of the Table per class hierarchy in the one class in the NHibernate/Conform

58 views Asked by At

I faced with following case: I have table per class hierarchy:

public abstract class Parent : BaseEntity, IHierarchyEntity
    {
    }  

public class ChildA : Parent
{
    public virtual string Name { get; set; }
}

public class ChildB : Parent
{
    public virtual string Value { get; set; }
}

public class Container : BaseEntity
{
    public Container()
    {
        CollectionOne = new HashSet<ChildA>();
        CollectionTwo = new HashSet<ChildB>();
    }

    public virtual ICollection<ChildA> CollectionOne { get; set; }

    public virtual ICollection<ChildB> CollectionTwo { get; set; }
}

Small piece of Domain mapper logic (it`s almost the same):

IEnumerable<Type> allPersistEntities = GetDomainEntities();
IEnumerable<Type> roots = allPersistEntities.Where(t => t.IsAbstract && t.InheritedFromBaseEntity());
IEnumerable<Type> hierarchyEntities = allPersistEntities.Where(t => typeof(IHierarchyEntity).IsAssignableFrom(t));
var hierarchyRoots = hierarchyEntities.Where(t => t.IsAbstract && t.InheritedFromBaseEntity());
orm.TablePerClassHierarchy(hierarchyRoots);

When I saved items everything is ok, but when I tried to get ones I get two of them in the CollectionOne (ChildA type) and error in the second one:

illegal access to loading collection What I see in the sql:

NHibernate:
    SELECT
        container0_.Id as Id0_0_
    FROM
        CONTAINERS container0_
    WHERE
        container0_.Id=@p0;
    @p0 = 1 [Type: Int32 (0)] NHibernate:
    SELECT
        collection0_.ContainerId as Containe5_1_,
        collection0_.Id as Id1_,
        collection0_.Id as Id1_0_,
        collection0_.Name as Name1_0_
    FROM
        PARENTS collection0_
    WHERE
        collection0_.ContainerId=@p0;
    @p0 = 1 [Type: Int32 (0)] NHibernate:
    SELECT
        collection0_.ContainerId as Containe5_1_,
        collection0_.Id as Id1_,
        collection0_.Id as Id1_0_,
        collection0_.[Value] as Value3_1_0_
    FROM
        PARENTS collection0_
    WHERE
        collection0_.ContainerId=@p0;
    @p0 = 1 [Type: Int32 (0)]

There is no discriminator field. Is it possible to fix it?

1

There are 1 answers

2
h.alex On

Can you try:

var hierarchyRoots = hierarchyEntities.Except(roots);

I think you might need to give it the exact leafs to map, I don't think it'll assume it should map all classes inheriting from the root as tpch.