Map a non-polymorphic association with Fluent NHibernate ReferencesAny
Asked Answered
B

0

8

Say we have two classes that each implement an interface, IParent, as follows:

public class Foo : IParent
{
    public long Id { get; set; }
    ...
    public IList<Child> Children { get; set; }
    ...
}
public class Bar : IParent
{
    public long Id { get; set; }
    ...
    public IList<Child> Children { get; set; }
    ...
}

And a child class that has a parent property of the type IParent, i.e. the parent could be either a Foo or a Bar:

public class Child
{
    public long Id { get; set; }
    ...
    public IParent Parent { get; set; }
    ...
}

How can this Parent property be mapped with FluentNHibernate?

I found this question which seemed to have similar requirements, but did not involve interfaces. The answer does not really make sense to me, or seem applicable in this case.

I have tried implementing the mapping using ReferencesAny, as follows:

public class ChildMap : ClassMap<Child>
{
    public ChildMap()
    {
        Table("children");
        Id(x => x.Id).GeneratedBy.Assigned();
        ...
        ReferencesAny(x => x.Parent)
            .AddMetaValue<Foo>(typeof(Foo).Name)
            .AddMetaValue<Bar>(typeof(Bar).Name)
            .EntityTypeColumn("parent_name")
            .EntityIdentifierColumn("parent_id")
            .IdentityType<long>()
            .LazyLoad();
    }
}

This does not cause any error when saving, but no data is written to the child table in the database, leading me to believe I have implemented the mapping incorrectly.

Bradley answered 29/8, 2017 at 16:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.