Tom
Tom

Reputation: 89

NHibernate Multiple Parents with same Child Entity Reference-to-Parent

I have a data structure with two parents, that can have children of the same class (entity) type.

public class Parent1 : BaseParent
{
    public Parent1()
    {
        Childs1 = new List<Child>();
    }
    public virtual IList<Child> Child1 { get; set; }
}

public class Parent2 : BaseParent
{
    public Parent2()
    {
        Childs2 = new List<Child>();
    }
    public virtual IList<Child> Child2 { get; set; }
}

public class Child
{
    public virtual BaseParent Parent { get; set; }
}

The Child should have a reference to its parent, whose collection it belongs to. That means, if Child is in the collection of Parent1.Childs1, Child.Parent should reference to Parent1. If Child is in the collection of Parent2.Childs2, Child.Parent should reference to Parent2.

I tried with

public class Parent1Map: ClassMap<Parent1>
{
    public Parent1Map()
    {
        Table("PARENT1");
        :
        HasMany<Child>(x => x.Child1).KeyColumn("PARENT1REF");
    }
}

public class Parent2Map: ClassMap<Parent2>
{
    public Parent2Map()
    {
        Table("PARENT2");
        :
        HasMany<Child>(x => x.Child1).KeyColumn("PARENT2REF");
    }
}

public class ChildMap: ClassMap<Child>
{
    public ChildMap()
    {
        Table("CHILD");
        :
        References<Parent1>(c => c.Parent).Column("PARENT1REF");
        References<Parent2>(c => c.Parent).Column("PARENT2REF");
    }
}

But this does not work. I geht the error Tried to add many-to-one 'Parent' when already added.

How can I do the mapping, so that the parent references of the childs are loaded correctly from the database?

Upvotes: 2

Views: 1105

Answers (1)

Firo
Firo

Reputation: 30813

i had a similar problem and went with referenceany. It's only applicable if child is never in more than one collection.

// ChildMap
ReferencesAny(result => result.Parent)
    .EntityTypeColumn("discriminator")
    .EntityIdentifierColumn("Parent_id")
    .IdentityType<long>()
    .AddMetaValue<Parent1>("parent1")
    .AddMetaValue<Parent2>("parent2");


// parent1map
HasMany(part => part.Childs)
    .Where("discriminator = 'parent1'");

Upvotes: 2

Related Questions